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?
To binary:
Here how to do it using
format()
using python format string syntax
The second line is where the magic happens. All byte objects have a
.hex()
function, which returns a hex string. Using this hex string, we convert it to an integer, telling theint()
function that it's a base 16 string (because hex is base 16). Then we apply formatting to that integer so it displays as a binary string. The{:08b}
is where the real magic happens. It is using the Format Specification Mini-Languageformat_spec
. Specifically it's using thewidth
and thetype
parts of the format_spec syntax. The8
setswidth
to 8, which is how we get the nice 0000 padding, and theb
sets the type to binary.I prefer this method over the
bin()
method because using a format string gives a lot more flexibility.