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?
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?
The other answers here provide the bits in big-endian order (
'\x01'
becomes'00000001'
)In case you're interested in little-endian order of bits, which is useful in many cases, like common representations of bignums etc - here's a snippet for that:
And for the other direction:
What about something like this?
This will convert the hexadecimal string you have to an integer and that integer to a string in which each byte is set to 0/1 depending on the bit-value of the integer.
As pointed out by a comment, if you need to get rid of the
0b
prefix, you can do it this way:or this way:
Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.
If you want bit 7 and 8 only, use e.g.
(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits
3
is the number with the first two bits set...)These can easily be translated into simple CPU operations that are super fast.
Another way to do this is by using the
bitstring
module:And if you need to strip the leading
0b
: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:etc.
I think simplest would be use
numpy
here. For example you can read a file as bytes and then expand it to bits easily like this:Use
ord
when reading reading bytes:Or
Using
str.format()
: