Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from hexadecimal to binary values

Am converting a value from hexadecimal to binary value.I used bin() of python like this:

value = 05808080
print bin(int(value, 16))

output i got is 0b101100000001000000010000000(output should be 32 bit)
output should be 0000 0101 1000 0000 1000 0000 1000 0000(correct output)

What is this 'b' in the output and how can i replace it with correct binary values.I think two values up here is almost same except issue with "b" in output.How will i resolve this ?

like image 428
Vishnu Avatar asked Jan 02 '26 05:01

Vishnu


1 Answers

The output you get is correct, it just needs to be formatted a bit. The leading 0b indicates that it is a binary number, similarly to how 0x stands for hexadecimal and 0 for octal.

First, slice away the 0b with [2:] and use zfill to add leading zeros:

>>> value = '05808080'
>>> b = bin(int(value, 16))
>>> b[2:]
'101100000001000000010000000'
>>> b[2:].zfill(32)
'00000101100000001000000010000000'

Finally, split the string in intervals of four characters and join those with spaces:

>>> s = b[2:].zfill(32)
>>> ' '.join(s[i:i+4] for i in range(0, 32, 4))
'0000 0101 1000 0000 1000 0000 1000 0000'

If you can live without those separator spaces, you can also use a format string:

>>> '{:032b}'.format(int(value, 16))
'00000101100000001000000010000000'
like image 170
tobias_k Avatar answered Jan 05 '26 05:01

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!