icon

Convert Int to Bytes in Python

Last modified: 2023-08-29

Conversion

Using the to_bytes built-in method in Python, we can conavert int to bytes.
In addition, we can specify the length to the first argument in to_bytes method.

Big Endian

By specifying 'big' to the byteorder argument, the result is the big endian bytes order.

num = 1234

num.to_bytes(2, byteorder='big')
# b'\x04\xd2'

num.to_bytes(3, byteforder='big')
# b'\x00\x04\xd2'

num.to_bytes(4, byteorder='big')
# b'\x00\x00\x04\xd2'

Little Endian

By specifying 'big' to the byteorder argument, the result is the little endian bytes order.

num = 1234

num.to_bytes(2, byteorder='little')
# b'\xd2\x04

num.to_bytes(3, byteorder='little')
# b'\xd2\x04\x00'

num.to_bytes(4, byteorder='little')
# b'\xd2\x04\x00\x00'