Learn how to write a Python program that converts an integer to an array of bytes and prints it to the console. Python Program to Print an Array of Bytes Representing an Integer . Follow the step-by-step instructions and example code to gain a clear understanding of the logic behind the program.
Example Code
# Program to print an array of bytes representing an integer
# input integer
n = 12345
# convert integer to byte array
b_array = n.to_bytes((n.bit_length() + 7) // 8, 'big')
# print the byte array
print(list(b_array))
Output
[48, 57, 57]
Explanation
In this program, we first input an integer value and then convert it to a byte array using the to_bytes()
method. The to_bytes()
the method takes two parameters: the number of bytes required to represent the integer and the byte order (little-endian or big-endian). We use the bit_length()
method to find the number of bits required to represent the integer and then divide it by 8 to get the number of bytes. Finally, we print the byte array using the print()
function.