How to Convert Int to Bytes in Python?
An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array.
Method 1: int.tobytes()
An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.
Syntax: int.to_bytes(length, byteorder)
length – desired length of the array in bytes .
byteorder – order of the array to carry out conversion of an int to bytes. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end.
OverflowError is returned in case the integer value length is not large enough to be accommodated in the length of the array.
The following programs illustrate the usage of this method in Python :
Method 2: Converting integer to string and string to bytes
This approach works is compatible in both Python versions, 2 and 3. This method doesn’t take the length of the array and byteorder as arguments.
- An integer value represented in decimal format can be converted to string first using the str() function , which takes as argument the integer value to be converted to the corresponding string equivalent.
- This string equivalent is then converted to a sequence of bytes by choosing the desired representation for each character, that is encoding the string value. This is done by the str.encode() method.