tags:

views:

63

answers:

2

I have a hex value in a string like

h = '00112233aabbccddee'

I know I can convert this to binary with:

h = bin(int(h, 16))[2:]

However, this loses the leading 0's. Is there anyway to do this conversion without losing the 0's? Or is the best way to do this just to count the number of leading 0's before the conversion then add it in afterwards.

+4  A: 

I don't think there is a way to keep those leading zeros by default.

Each hex digit translates to 4 binary digits, so the length of the new string should be exactly 4 times the size of the original.

h_size = len(h) * 4

Then, you can use .zfill to fill in zeros to the size you want:

h = ( bin(int(h, 16))[2:] ).zfill(h_size)
orangeoctopus
I think this gave me 3 extra 0's for some reason
root
Ah nevermind it works perfectly. I wasn't counting the 0's before the first non zero hex number. Thanks.
root
A: 

Basically the same but padding to 4 bindigits each hexdigit

''.join(bin(c)[2:].zfill(4) for c in h)
Nas Banov