0

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!'

1 Answer 1

2

No leading zero bytes in the result:

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.

Fixed length result (with leading zeros if necessary):

Starting with Python 3.2 you can use int.to_bytes which also supports little-endian byte order.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.