将字节转换为python中的位 [英] Convert bytes to bits in python
问题描述
我正在使用Python3.2。我需要将十六进制流作为输入并在比特级解析它。所以我使用了
bytes.fromhex(input_str)
将字符串转换为实际字节。现在我该如何将这些字节转换为位?解析方案
另一种方法是使用 bitstring
模块:
>>> from bitstring import BitArray
>>> input_str ='0xff'
>>> c = BitArray(hex = input_str)
>>> c.bin
'0b11111111'
如果你需要去掉领先的 0b
:
>>> c.bin [2:]
'11111111'
>>> c.uint
255
>>> c.invert()
>>> c.bin [2:]
'00000000'
等。
I am working with Python3.2. I need to take a hex stream as an input and parse it at bit-level. So I used
bytes.fromhex(input_str)
to convert the string to actual bytes. Now how do I convert these bytes to bits?
Another way to do this is by using the bitstring
module:
>>> from bitstring import BitArray
>>> input_str = '0xff'
>>> c = BitArray(hex=input_str)
>>> c.bin
'0b11111111'
And if you need to strip the leading 0b
:
>>> c.bin[2:]
'11111111'
The bitstring
module isn't a requirement, as jcollado's answer shows, but it has lots of performant methods for turning input into bits and manipulating them. You might find this handy (or not), for example:
>>> c.uint
255
>>> c.invert()
>>> c.bin[2:]
'00000000'
etc.
这篇关于将字节转换为python中的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!