.to_bytes() method is used to convert an integer into its byte representation.This is useful when we need to store or transmit data in binary format.
Example: Convert the integer 10 into bytes.
num = 10
data = num.to_bytes(2, 'little')
print(data)
Output
b'\n\x00'
Explanation: num.to_bytes(2, 'little') converts integer 10 into 2 bytes using little-endian order.
Note: The byte 0x0A represents decimal 10. Python prints this byte as \n because it corresponds to the newline character.
Syntax
int.to_bytes(length, byteorder, *, signed=False)
Parameters:
- length: The number of bytes the integer should occupy.
- byteorder: The byte order used to represent the integer. It can be: 'big': Most significant byte first (big-endian). 'little': Least significant byte first (little-endian).
- signed: (Optional) If True, allows the representation of negative numbers. Default is False (unsigned).
Return Type: Returns a bytes object representing the integer in the specified format.
Examples
1. Using Little-Endian
num = 10
data = num.to_bytes(2, 'little')
print(data)
Output
b'\n\x00'
Explanation:
- num.to_bytes(2, 'little'): converts 10 into 2 bytes using little-endian order.
- The byte 0x0A represents decimal 10. Python displays it as \n because that is its ASCII character, but it is still the numeric value 10.
2. Representing Negative Numbers
num = -10
data = num.to_bytes(2, 'big', signed=True)
print(data)
Output
b'\xff\xf6'
Explanation:
- Converts -10 into a 2-byte big-endian bytes object using two’s complement.
- signed=True: is necessary to represent negative numbers.
3. Converting Bytes Back to Integer
data = b'\x00\x0a'
num = int.from_bytes(data, 'big')
print(num)
Output
10
Explanation:
- int.from_bytes(data, 'big'): converts a bytes object back into an integer.
- 'big': Big-endian byte order (most significant byte first).