Reputation: 13260
How can I convert an arbitrary length (positive) integer into a bytes object in Python 3? The most significant byte should be first so that it is basically a base 256 encoding.
For fixed length values (up to unsigned long long) you can use the struct module but there seems to be no library support for conversions of large numbers in Python.
Expected results:
>>> intToBytes(5)
b'\x05'
>>> intToBytes(256)
b'\x01\x00'
>>> intToBytes(6444498374093663777)
b'You won!'
Upvotes: 0
Views: 1811
Reputation: 13260
def intToBytes(num):
if num == 0:
return b""
else:
return intToBytes(num//256) + bytes([num%256])
or as a one-liner
intToBytes = lambda x: b"" if x==0 else intToBytes(x//256) + bytes([x%256])
Consecutively concatenating the constant bytes objects is not terribly efficient but makes the code shorter and more readable.
As an alternatve you can use
intToBytes = lambda x: binascii.unhexlify(hex(x)[2:])
which has binascii
as dependency, though.
Starting with Python 3.2 you can use int.to_bytes which also supports little-endian byte order.
Upvotes: 2