简体   繁体   中英

Convert binary string to hex string and keep its leading zeros

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM