.to_bytes() in Python
In Python, the .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
byte_data = num.to_bytes(2, 'little')
print(byte_data)
Output
b'\n\x00'
Explanation:
- 10: The integer being converted.
- .to_bytes(2, 'little'):
2 specifies the byte length (2 bytes).
'little' means least significant byte first (little-endian). - b'\n\x00': The byte representation of 10 in little-endian format. Here:
\n is hexadecimal 0x0a (decimal 10)
\x00 is the second byte (0).
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 of .to_bytes() method
1. Using Little-Endian
num = 10
byte_rep = num.to_bytes(2, 'little')
print(byte_rep)
Output
b'\n\x00'
Explanation:
- 10 in binary is 00001010, and in little-endian, it is represented as b'\n\x00'.
- The b'\n\x00' output shows that 10 is stored as \n (10 in hexadecimal) followed by \x00 (a zero byte).
2. Representing Negative Numbers
num = -10
byte_rep = num.to_bytes(2, 'big', signed=True)
print(byte_rep.hex())
Output
fff6
Explanation:
- -10 in two's complement (signed) using big-endian is represented as b'\xff\xf6'.
- The b'\xff\xf6' output indicates that -10 is stored using two bytes where the first byte is 0xFF (representing the negative sign) and the second byte is 0xF6 (which is -10 in two's complement form).
3. Converting bytes back to integer
byte_data = b'\x00\x0a'
num = int.from_bytes(byte_data, 'big')
print(num)
Output
10
Explanation:
- b'\x00\x0a' represents the byte sequence where the first byte is 0x00 (0 in decimal) and the second byte is 0x0a (10 in decimal).
- Using big-endian byte order, this byte sequence is converted to the integer 10.