user3431399
user3431399

Reputation: 499

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.

Upvotes: 1

Views: 2289

Answers (1)

Stefan Pochmann
Stefan Pochmann

Reputation: 28626

Just divide the number of bits by 4:

>>> bits = "0000000000001010"
>>> '{:0{}X}'.format(int(bits, 2), len(bits) // 4)
'000A'

Upvotes: 5

Related Questions