2

I have a bit-string of 32 characters that I need to represent as hexadecimal in Python. For example, the string "10000011101000011010100010010111" needs to also be output as "83A1A897".

Any suggestions on how to best go about this in Python?

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
Chris Wiegman
  • 382
  • 1
  • 2
  • 10
  • Possible duplicate of [Python conversion from binary string to hexadecimal](http://stackoverflow.com/questions/2072351/python-conversion-from-binary-string-to-hexadecimal) – Cees Timmerman Apr 23 '17 at 19:32

5 Answers5

24

To format to hexadecimal you can use the hex function:

>>> hex(int('10000011101000011010100010010111', 2))
0x83a1a897

Or to get it in exactly the format you requested:

>>> '%08X' % int('10000011101000011010100010010111', 2)
83A1A897
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3
>>> binary = '10010111'
>>> int(binary,2)
151
>>> hex(int(binary,2))
'0x97'

I hope this helps!

VoronoiPotato
  • 3,113
  • 20
  • 30
2

You can do this very easy with build in functions. The first thing you want to do is convert your binary to an integer:

>> int("1010",2)
10

The second step then would be to represent this as hex:

>> "%04X" % int("1010",2)
'000A'

in case you don't want any predefined length of the hex string then just use:

>> "%X" % int("1010",2)
'A'
>> "0x%X" % int("1010",2)
'0xA'
sebs
  • 4,566
  • 3
  • 19
  • 28
  • This is the correct answer. `hex(int("10", 2))` also works, but the main point is that you have to pass in a value for the second parameter for the int function. Its signature is `def __init__(self, x, base=10):` – Jeff Feb 06 '18 at 00:13
0

Well we could string format just like Mark Byers said.Or in other way we could string format in another method like given below:

>>> print('{0:x}'.format(0b10000011101000011010100010010111))
83a1a897

To make the alphabets between the hex in upper case try this:

>>> print('{0:X}'.format(0b10000011101000011010100010010111))
83A1A897

Hope this is helpful.

0

To read in a number in any base use the builtin int function with the optional second parameter specifying the base (in this case 2).

To convert a number to a string of its hexadecimal form just use the hex function.

>>> number=int("10000011101000011010100010010111",2)
>>> print hex(number)
0x83a1a897L
MAK
  • 26,140
  • 11
  • 55
  • 86