How to Convert Int to Bytes in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To convert an integer to a byte string in Python, you can use the int.to_bytes() method. The int.to_bytes() method returns a byte string representation of an integer. Here’s an example:

n = 12345
byte_string = n.to_bytes(2, byteorder='big')
print(byte_string)

In this example, we convert the integer 12345 to a byte string using int.to_bytes(). The byte string is two bytes long (length 2), and we specify the byte order as 'big'. The resulting byte string is then printed to the console.

Note that int.to_bytes() takes two arguments: the number of bytes in the resulting byte string, and the byte order (‘big’ or ‘little’). You should choose the byte order that is appropriate for your application.

Tags:

related content