To convert an integer to bytes in Python, you can use the Python int to_bytes() function. to_bytes converts an int object into an array of bytes representing that integer.
num = 10
num_bytes = num.to_bytes(3, byteorder="big")
print(num_bytes)
#Output:
b'x00x00n'
When working with different types of objects when programming, the ability to easily be able to convert a variable into a variable of another type is useful.
One such case is if you want to convert an integer to bytes in Python.
Converting an integer to bytes in Python is easy. To convert integers to bytes, you can use the Python int to_bytes() function.
to_bytes converts an int object into an array of bytes representing that integer.
to_bytes takes in three arguments. The first argument is the number of bytes you want returned for representing the integer.
The second argument is the order of bytes. You can pass “little” or “big” to “byteorder”. The difference here is passing “little” will result in having the most significant byte at the end of the array, while “big” will result in having the most significant byte at the beginning of the array.
If you want to go the other way and convert a byte to an integer, this order will matter!
The third argument is used if you have a negative number and want to convert a negative number into bytes.
Below are some examples showing you how to convert integers to bytes with to_bytes() in Python.
num1 = 5
num2 = 10
num3 = -5
print(num1.to_bytes(1, byteorder="big"))
print(num1.to_bytes(2, byteorder="big"))
print(num1.to_bytes(3, byteorder="little"))
print(num2.to_bytes(1, byteorder="big"))
print(num2.to_bytes(2, byteorder="big"))
print(num2.to_bytes(3, byteorder="big"))
print(num3.to_bytes(1, byteorder="little", signed=True))
#Output:
b'x05'
b'x00x05'
b'x05x00x00'
b'n'
b'x00n'
b'x00x00n'
b'xfb'
Hopefully this article has been useful for you to learn how to convert an integer to a bytes object in Python with to_bytes().