Python is a high-level programming language that provides functionalities for several operations. The array
module comes with various methods to manipulate array data structures.
The array.tobytes()
function returns the binary representation of the given array. This binary representation is used for efficient and consistent data storage.
bytes = array.tobytes()
Each integer value is stored in 32 bits, which is represented in the hexadecimal format, as shown in the diagram above.
This function does not take in any arguments.
This function returns a string containing the byte representation of the array.
Let’s look at the code below:
#import moduleimport array#initialize arrayarray_one = array.array('i', [1, 2, 255, 255])array_two = array.array('i', [65535])#print arrayprint(array_one)print(array_two)#convert array to byte stringbytes_one = array_one.tobytes()bytes_two = array_two.tobytes()#print byte stringprint(bytes_one)print(bytes_two)
Line 2: We import the array
module.
Lines 5 and 6: We initialize arrays with integer values.
Lines 13 and 14: We convert the arrays of integers to strings containing bytes representation using tobytes()
method.
The bytes representation in the 32-bit hexadecimal values is printed in the output. For example, the value of the bytes corresponding to 255
is xff\x00\x00\x00
, and for 0
, it’s x00\x00\x00\x00
.