python 3.x - Arbitrary length integer to byte array conversion (Most significant byte first) -


how can convert arbitrary length (positive) integer bytes object in python 3? significant byte should first base 256 encoding.

for fixed length values (up unsigned long long) can use struct module there seems no library support conversions of large numbers in python.

expected results:

>>> inttobytes(5) b'\x05' >>> inttobytes(256) b'\x01\x00' >>> inttobytes(6444498374093663777) b'you won!' 

no leading 0 bytes in result:

def inttobytes(num):     if num == 0:         return b""     else:         return inttobytes(num//256) + bytes([num%256]) 

or one-liner

inttobytes = lambda x: b"" if x==0 else inttobytes(x//256) + bytes([x%256]) 

consecutively concatenating constant bytes objects not terribly efficient makes code shorter , more readable.

as alternatve can use

inttobytes = lambda x: binascii.unhexlify(hex(x)[2:]) 

which has binascii dependency, though.

fixed length result (with leading zeros if necessary):

starting python 3.2 can use int.to_bytes supports little-endian byte order.


Comments