Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在压缩二进制数据Python中解释5bit子集_Python_Binary - Fatal编程技术网

在压缩二进制数据Python中解释5bit子集

在压缩二进制数据Python中解释5bit子集,python,binary,Python,Binary,这件事我真的有点麻烦有一段时间了。我在python中接收到一个二进制数据字符串,并且我在解包和解释数据的5位子集(而不是整个字节)时遇到困难。似乎任何想到的方法都会失败得很惨 假设我有两个字节的压缩二进制数据,我想解释16个字节中的前10位。如何将其转换为2个整数,每个整数代表5位?使用位掩码和位移位: >>> example = 0x1234 # Hexadecimal example; 2 bytes, 4660 decimal. >>> bin(ex

这件事我真的有点麻烦有一段时间了。我在python中接收到一个二进制数据字符串,并且我在解包和解释数据的5位子集(而不是整个字节)时遇到困难。似乎任何想到的方法都会失败得很惨


假设我有两个字节的压缩二进制数据,我想解释16个字节中的前10位。如何将其转换为2个整数,每个整数代表5位?

使用位掩码和位移位:

>>> example = 0x1234   # Hexadecimal example; 2 bytes, 4660 decimal.
>>> bin(example)       # Show as binary digits
'0b1001000110100'
>>> example & 31       # Grab 5 most significant bits
20
>>> bin(example & 31)  # Same, now represented as binary digits
'0b10100'
>>> (example >> 5) & 31 # Grab the next 5 bits (shift right 5 times first)
17
>>> bin(example >> 5 & 31)
'0b10001'
这里的技巧是知道31是一个5位位位掩码:

>>> bin(31)
'0b11111'
>>> 0b11111
31
>>> example & 0b11111
20
如您所见,如果您发现二进制数文字表示法更易于使用,也可以使用
0b
二进制数文字表示法


有关更多背景信息,请参阅。

太棒了!这也很有道理。