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?
Sommaire |
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?
http://packages.python.org/bitstring/index.html# http://packages.python.org/bitstring/index.html#
>>> 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.
License : cc by-sa 3.0
http://stackoverflow.com/questions/8815592/convert-bytes-to-bits-in-python