Lan*_*doR 1 python bit-shift binary-data python-3.x
我试图从字节对象中提取数据.例如:从b'\x93\x4c\x00'我的整数隐藏从第8位到第21位.我试图这样做,bytes >> 3但这不可能有多个字节.我也尝试用struct解决这个问题,但字节对象必须具有特定的长度.
如何将位移到右边?
不要bytes用来表示整数值; 如果你需要位,转换为int:
value = int.from_bytes(your_bytes_value, byteorder='big')
bits_21_to_8 = (value & 0x1fffff) >> 8
Run Code Online (Sandbox Code Playgroud)
当0x1fffff面膜也可以用计算:
mask = 2 ** 21 - 1
Run Code Online (Sandbox Code Playgroud)
演示:
>>> your_bytes_value = b'\x93\x4c\x00'
>>> value = int.from_bytes(your_bytes_value, byteorder='big')
>>> (value & 0x1fffff) >> 8
4940
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下int.to_bytes()方法返回字节:
>>> ((value & 0x1fffff) >> 8).to_bytes(2, byteorder='big')
b'\x13L'
Run Code Online (Sandbox Code Playgroud)