Python 字节字符串和int的按位操作
我正在将一些cython代码转换为python,在我开始进行按位操作之前,它一直运行良好。以下是代码片段:Python 字节字符串和int的按位操作,python,python-2.7,bitwise-operators,bitstring,Python,Python 2.7,Bitwise Operators,Bitstring,我正在将一些cython代码转换为python,在我开始进行按位操作之前,它一直运行良好。以下是代码片段: in_buf_word = b'\xff\xff\xff\xff\x00' bits = 8 in_buf_word >>= bits 如果我运行此命令,它将抛出以下错误: TypeError: unsupported operand type(s) for >>=: 'str' and 'int' 如何解决这个问题?右移8位只意味着切断最右边的字节 由于您已经
in_buf_word = b'\xff\xff\xff\xff\x00'
bits = 8
in_buf_word >>= bits
如果我运行此命令,它将抛出以下错误:
TypeError: unsupported operand type(s) for >>=: 'str' and 'int'
如何解决这个问题?右移8位只意味着切断最右边的字节 由于您已经有了一个
bytes
对象,因此可以更轻松地执行此操作:
in_buf_word = in_buf_word[:-1]
您可以通过将字节转换为整数,将其移位,然后将结果转换回字节字符串来实现
in_buf_word = b'\xff\xff\xff\xff\x00'
bits = 8
print(in_buf_word) # -> b'\xff\xff\xff\xff\x00'
temp = int.from_bytes(in_buf_word, byteorder='big') >> bits
in_buf_word = temp.to_bytes(len(in_buf_word), byteorder='big')
print(in_buf_word) # -> b'\x00\xff\xff\xff\xff'
如果你没有。去你的候机楼
pip3 install bitstring --> python 3
pip install bitstring --> python 2
要将其转换回字节,请使用tobytes()方法:
你对此的预期结果是什么?这是一个固定的数量,还是可以是
2
,29
,33
,或者-1
?位不是一个固定的数量,但在我的情况下通常是8,然而在buf\u字是一种动态的东西。我如何将其转换回字节?@EmilBengtsson use tobytes()。例如,请参见编辑的答案
pip3 install bitstring --> python 3
pip install bitstring --> python 2
print(in_buf_word.tobytes())