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 3 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]: bytes.fromhex(hs)
Out[2]: b'\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(i) for i in b])
Out[3]: '38 F3 DC 19 60 ED B2 C2 1C 79 83 51 8F 6D 44 A4'

In [4]: import binascii

In [5]: binascii.hexlify(b)
Out[5]: b'38f3dc1960edb2c21c7983518f6d44a4'

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'

For comments, please send me an e-mail.


Related articles


Extracting data from XML with regular expressions  →