Python conversion from binary string to hexadecimal Python conversion from binary string to hexadecimal python python

Python conversion from binary string to hexadecimal


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]) -> integerConvert 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) -> stringReturn the hexadecimal representation of an integer or long

integer.


bstr = '0000 0100 1000 1101'.replace(' ', '')hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2))


Use python's binascii module

import binasciibinFile = open('somebinaryfile.exe','rb')binaryData = binFile.read(8)print binascii.hexlify(binaryData)