views:

305

answers:

5

how can I perform a conversion of a binary string to the corresponding hex value in python

I have 0000 0100 1000 1101 and I want to get 048D
I'm using python2.6

Thanks for the help

+4  A: 

Welcome to StackOverflow!

int given base 2 and then hex:

>>> int('010110', 2)
22
>>> hex(int('010110', 2))
'0x16'
>>> 

>>> hex(int('0000010010001101', 2))
'0x48d'

The doc of int:

int(x[, base]) -> integer

Convert a string or number to an integer, if possible.  A floating

point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If base is zero, the proper base is guessed based on the string content. If the argument is outside the integer range a long object will be returned instead.

The doc of hex:

hex(number) -> string

Return the hexadecimal representation of an integer or long

integer.

Eli Bendersky
This fails to preserve leading 0s.
Ignacio Vazquez-Abrams
@Ignacio, you're right, but I don't think the OP asked about that. In any case, ++ to your answer for pointing that out.
Eli Bendersky
@Eli: the OP specifically said he wanted `048d` i.e. wants leading zero, DOESN'T want 0x
John Machin
A: 

Assuming they are grouped by 4 and separated by whitespace. This preserves the leading 0.

b = '0000 0100 1000 1101'
h = ''.join(hex(int(a, 2))[2:] for a in b.split())
Tor Valamo
you don't need list comprehension there
SilentGhost
good point. dunno why I always do that.
Tor Valamo
+1  A: 
bstr = '0000 0100 1000 1101'.replace(' ', '')
hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2))
Ignacio Vazquez-Abrams
@SO should really add per-language coloring. Here it thinks // is a C++ comment and grays out everything following. // in Python isn't a comment, but truncating integer division
Eli Bendersky
A: 
>>> import string
>>> s="0000 0100 1000 1101"
>>> ''.join([ "%x"%string.atoi(bin,2) for bin in s.split() ]  )
'048d'
>>>

or

>>> s="0000 0100 1000 1101"
>>> hex(string.atoi(s.replace(" ",""),2))
'0x48d'
ghostdog74
Using the string module is so 1990s ...
John Machin
so what's the problem? Its still in Python 2.6
ghostdog74
It's still in 2.X for the benefit of people who were using it in 1.X. string.atoi() is according to the 2.6 docs """Deprecated since version 2.0: Use the int() built-in function.""" and is not present in 3.X. The 2.X implementation of string.atoi() calls int(). There is no good reason for telling some newcomer that string.atoi() even exists let alone telling them to use it instead of telling them to use int().
John Machin
+2  A: 

You could use the format() built-in function like this:

"{0:0>4X}".format(int("0000010010001101", 2))
Gareth Williams