How To/python/

How to convert integer to bytes in python

You can use functions given below or play with encode('hex')/decode('hex'). Remember that there are few methods for ordering bytes coding inegers. You have to use proper function for proper format. I have written functions only for big-endian and little-endian but you can find some others "endians".

Big-endian vs Little-endian

In big-endian bytes value rises from right to left (byte with biggest value is stored at the lowest address). In little-endian bytes values rises from left to right so byte with lowest value is stored at lowest address in memory.

Example (in python ** is power operator):

big-endian value:     0x12ac45fe
value rise direction: <---------
gives:
0xfe * 256**0 + 0x45 * 256**1 + 0xac * 256**2 + 0x12* 256**3 =
313279998 (int)

little-endian value:  0x12ac45fe
value rise direction: --------->
gives:
0x12 * 256**0 + 0xac * 256**1 + 0x45 * 256**2 + 0xfe* 256**3 =
4265978898 (int)

See also endianness on Wikipedia

Python code for converting int to bytes

'le' functions sre for little-endian and 'be' are for big endian byte order.

def lePack(n, l):
    """ Converts integer to bytes. If length after conversion
    is smaller than given as param returned value is right-filled
    with 0x00 bytes. Use Little-endian byte order."""
    return b''.join([
        chr((n >> ((l - i - 1) * 8)) % 256) for i in xrange(l)
    ][::-1])
 
 
def leUnpack(byte):
    """ Converts byte string to integer. Use Little-endian byte order."""
    return sum([
        ord(b) << (8 * i) for i, b in enumerate(byte)
    ])
 
 
def bePack(n, l):
    """ Converts integer to bytes. If length after conversion
    is smaller than given as param returned value is right-filled
    with 0x00 bytes. Use Big-endian byte order."""
    return b''.join([
        chr((n >> ((l - i - 1) * 8)) % 256) for i in xrange(l)
    ])
 
 
def beUnpack(byte):
    """ Converts byte string to integer. Use Big-endian byte order."""
    return sum([
        ord(b) << (8 * i) for i, b in enumerate(byte[::-1])
    ])

Example output:

>>> print lePack(258, 5).encode('hex')
0201000000
>>> print bePack(258, 5).encode('hex')
0000000102
>>> print leUnpack('\x02\x01\x00\x00\x00')
258
>>> print beUnpack('\x00\x00\x00\x01\x02')
258