字节串和int的位运算

问题描述 投票:0回答:1

我正在将一些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'

我该如何解决这个问题?

python python-2.7 bitwise-operators bitstring
1个回答
1
投票
import bitstring

in_buf_word = b'\xff\xff\xff\xff\x00'
bits = 8
in_buf_word  = bitstring.BitArray(in_buf_word ) >> bits

如果你没有它。去你的终端

pip3 install bitstring --> python 3
pip install bitstring --> python 2

要将其隐蔽回字节,使用 tobytes() 方法。

print(in_buf_word.tobytes())

0
投票

向右移动8位只是意味着切断最右边的字节。

因为你已经有了一个 bytes 对象,这可以更容易地完成。

in_buf_word = in_buf_word[:-1]

0
投票

你可以把字节转换成一个整数, 移位, 然后把结果转换成一个字节字符串.

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'
© www.soinside.com 2019 - 2024. All rights reserved.