Reputation: 499
May I know how to write a Python script to convert binary string to hexadecimal string and keep the leading zeros?
For an example, I have binary string "0000000000001010"
and would like to print it into "000A"
. I know i can use zfill()
function, but the number of leading zeros is unknown.
Upvotes: 1
Views: 2289
Reputation: 28626
Just divide the number of bits by 4:
>>> bits = "0000000000001010"
>>> '{:0{}X}'.format(int(bits, 2), len(bits) // 4)
'000A'
Upvotes: 5