Converting from hex to binary without losing leading 0's python
Solution 1
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)
Solution 2
This is actually quite easy in Python, since it doesn't have any limit on the size of integers. Simply prepend a '1'
to the hex string, and strip the corresponding '1'
from the output.
>>> h = '00112233aabbccddee'
>>> bin(int(h, 16))[2:] # old way
'1000100100010001100111010101010111011110011001101110111101110'
>>> bin(int('1'+h, 16))[3:] # new way
'000000000001000100100010001100111010101010111011110011001101110111101110'
Solution 3
Basically the same but padding to 4 bindigits each hexdigit
''.join(bin(int(c, 16))[2:].zfill(4) for c in h)
root
Updated on July 05, 2022Comments
-
root almost 2 years
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.
-
root almost 14 yearsI think this gave me 3 extra 0's for some reason
-
root almost 14 yearsAh nevermind it works perfectly. I wasn't counting the 0's before the first non zero hex number. Thanks.
-
jfs about 8 years@root: unrelated: don't reuse
h
name for different things e.g., usebits
name for the result:bits = bin(int(h, 16))[2:].zfill(len(h) * 4)
-
Alex Stewart almost 7 yearsBeen looking for exactly this for an hour!
-
foobar over 2 yearsWhy is this not an accepted answer.
-
Mark Ransom over 2 years@foobar you'll notice it was posted 3 years after the accepted answer - don't remember what prompted me to make an answer.