Chris Wiegman
Chris Wiegman

Reputation: 382

How do I convert a string of bits to a hex string in Python?

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?

Upvotes: 2

Views: 29622

Answers (5)

user4549470
user4549470

Reputation:

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.

Upvotes: 0

sebs
sebs

Reputation: 4776

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'

Upvotes: 2

VoronoiPotato
VoronoiPotato

Reputation: 3183

>>> binary = '10010111'
>>> int(binary,2)
151
>>> hex(int(binary,2))
'0x97'

I hope this helps!

Upvotes: 3

MAK
MAK

Reputation: 26586

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

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 839114

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

Upvotes: 24

Related Questions