Given an integer number and we have to convert it into a byte array in Python.
To convert an integer number into bytes (byte array), we use to_bytes() method of int class, it is called with the number with three arguments and returns a byte array representing the number.
Syntax:
int.to_bytes(size, byteorder)
Here,
- size is the maximum size (in bytes) of the number.
- byteorder is the technique to print the bytes, it has two values big to print bytes array in big-endian format and little to print bytes array in little-endian format.
Example:
Input:
num = 100
# function call
print(num.to_bytes(2, byteorder ='big'))
Output:
b'\x00d'
Python code to convert an integer number to bytes array
Output
If number is longer than 2 bytes value,
If the input number is larger than 2 bytes and we used size "2 bytes" with the to_bytes() method, then an "OverflowError" error ("int too big to convert") will occur.
to_bytes() array with size "4 bytes"
In the previous example, we used size "2 bytes", if the number is larger than it, we can increase the size. Here, in this example – we are using size "4 bytes", thus, we can convert an integer till 4 bytes.
Output
Printing the bytes array in little-endian format
To print bytes array of an integer number, we can define byteorder value with little. In this example, we are converting an integer number (till 4 bytes) to bytes array in little-endian order.
Output
need an explanation for this answer? contact us directly to get an explanation for this answer