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.
Just divide the number of bits by 4:
>>> bits = "0000000000001010"
>>> '{:0{}X}'.format(int(bits, 2), len(bits) // 4)
'000A'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.