def num_to_bytes(num):
    num = hex(num)[2:].rstrip('L')
if len(num) % 2:
    return ('0%s' % num).decode('hex')
return num.decode('hex')

def bytes_to_num(bytes):
    return int(bytes.encode('hex'), 16)
Efficient arbitrary-sized integer packing in Python