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
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
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.
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())
bstr = '0000 0100 1000 1101'.replace(' ', '')
hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2))
>>> 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'
You could use the format() built-in function like this:
"{0:0>4X}".format(int("0000010010001101", 2))