1

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.

1
  • Is it guranteed that the string's length is divisible by 4? Commented May 9, 2015 at 18:05

1 Answer 1

5

Just divide the number of bits by 4:

>>> bits = "0000000000001010"
>>> '{:0{}X}'.format(int(bits, 2), len(bits) // 4)
'000A'
Sign up to request clarification or add additional context in comments.

1 Comment

thrilled to see that int() can take a base!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.