In Python, you can convert an integer to bytes using the to_bytes()
method. This method returns a byte representation of the integer in a specified number of bytes.
Here is an example of how to use to_bytes()
:
# Example integer
integer_value = 12345
# Convert integer to bytes
# Parameters: number of bytes, byte order ('big' or 'little')
byte_value = integer_value.to_bytes((integer_value.bit_length() + 7) // 8, 'big')
print(byte_value) # Output: b'\x30\x39'
Parameters of to_bytes()
:
- length (int): The number of bytes to represent the integer. If the integer is large, you’ll need to increase the byte length.
- byteorder (str): This determines the byte order used to represent the integer. It can either be
'big'
(most significant byte first) or'little'
(least significant byte first).
Example usage:
- Integer to bytes (big-endian):
integer_value.to_bytes(4, 'big')
converts the integer into 4 bytes with the most significant byte first. - Integer to bytes (little-endian):
integer_value.to_bytes(4, 'little')
converts the integer into 4 bytes with the least significant byte first.
If you want to convert back from bytes to an integer, you can use the int.from_bytes()
method:
# Convert bytes back to integer
int_value = int.from_bytes(byte_value, 'big')
print(int_value) # Output: 12345