def int_to_bytes(n, minlen=0):  # helper function
    """ int/long to bytes (little-endian byte order).
        Note: built-in int.to_bytes() method could be used in Python 3.
    """
    nbits = n.bit_length() + (1 if n < 0 else 0)  # plus one for any sign bit
    nbytes = (nbits+7) // 8  # number of whole bytes
    ba = bytearray()
    for _ in range(nbytes):
        ba.append(n & 0xff)
        n >>= 8
    if minlen > 0 and len(ba) < minlen:  # zero pad?
        ba.extend([0] * (minlen-len(ba)))
    return ba