Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python conversion from binary string to hexadecimal

Tags:

python

hex

binary

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 Python 2.6.

like image 560
sylvain Avatar asked Jan 15 '10 14:01

sylvain


People also ask

How do you print decimal binary octal hexadecimal in Python?

Source Code # Python program to convert decimal into other number systems dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") print(oct(dec), "in octal.") print(hex(dec), "in hexadecimal.") The decimal value of 344 is: 0b101011000 in binary. 0o530 in octal.


1 Answers

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.

like image 77
Eli Bendersky Avatar answered Sep 19 '22 21:09

Eli Bendersky