Roland's homepage

My random knot in the Web

Python number conversions

Sometimes one has to convert numbers from and to different formats. Below are some examples in Python that I picked up over time. What you see are excerpts of IPython sessions.

To and from hexadecimal (base 16):

In [1]: hex(100)
Out[1]: '0x64'

In [2]: int(0xa7)
Out[2]: 167

From any base to integer:

In [1]: int('1010', base=2)
Out[1]: 10

In [2]: int('0xa7', base=16)
Out[2]: 167

In [3]: int('a7', base=16)
Out[3]: 167

From hexadecimal to bytes;

In [1]: hs = "AE 68 52 F8 12 10 67 CC 4B F7 A5 76 55 77 F3 9E"

In [2]: str(bytearray.fromhex(hs))
Out[2]: '\xaehR\xf8\x12\x10g\xccK\xf7\xa5vUw\xf3\x9e'

Note

There are other methods to do this, but this one skips the whitespace automatically.

From bytes to hex string;

In [1]: import os

In [2]: b = os.urandom(16)

In [3]: ' '.join(['{:02X}'.format(ord(i)) for i in b])
Out[3]: 'C7 37 72 C9 D8 C0 D6 81 D4 E0 51 56 D5 3D B3 95'

In [4]: b.encode('hex')
Out[4]: 'c73772c9d8c0d681d4e05156d53db395'

In [5]: import binascii

In [6]: binascii.hexlify(b)
Out[6]: 'c73772c9d8c0d681d4e05156d53db395'

Note

In Python 3 the ‘hex’ codec has been removed.

The binascii module has a lot of other goodies as wel.

From hexadecimal to decimal string;

In [1]: hs = "AE 68 52 F8 12 10 67 CC 4B F7 A5 76 55 77 F3 9E"

In [2]: ' '.join([str(int(n, base=16)) for n in hs.split()])
Out[2]: '174 104 82 248 18 16 103 204 75 247 165 118 85 119 243 158'

Extracting data from XML with regular expressions  →