Thursday, April 10, 2014

Convert values to / from integer, hex string and raw data in Python 2.x / 3.x

I often use quick and dirty Python scripts to deal with binary protocols dissection, packet capture analysis, and to work with raw binary files.

If you are in the same situation, you may find this useful. Just keep the following library somewhere and use it whenever needed in your scripts.

No external libraries are required, and it works natively with Python 2 and 3.

Note however that it can be prone to unwanted behaviour. For example, if you call int2bytes() with an input integer between 2^16 and 2^24, it will return 3 bytes, while you probably want 4 (with a leading "\x00"). Just keep that in mind.

def bytes2int(str):
 return int(str.encode('hex'), 16)

def bytes2hex(str):
 return '0x'+str.encode('hex')

def int2bytes(i):
 h = int2hex(i)
 return hex2bytes(h)

def int2hex(i):
 return hex(i)

def hex2int(h):
 if len(h) > 1 and h[0:2] == '0x':
  h = h[2:]

 if len(h) % 2:
  h = "0" + h

 return int(h, 16)

def hex2bytes(h):
 if len(h) > 1 and h[0:2] == '0x':
  h = h[2:]

 if len(h) % 2:
  h = "0" + h

 return h.decode('hex')

No comments:

Post a Comment