Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is an array.tobytes() in Python?

Eman Kashif

Overview

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.

Syntax

bytes = array.tobytes()

Each integer value is stored in 32 bits, which is represented in the hexadecimal format, as shown in the diagram above.

Parameters

This function does not take in any arguments.

Return value

This function returns a string containing the byte representation of the array.

Code example

Let’s look at the code below:

#import module
import array

#initialize array
array_one = array.array('i', [1, 2, 255, 255])
array_two = array.array('i', [65535])

#print array
print(array_one)
print(array_two)

#convert array to byte string
bytes_one = array_one.tobytes()
bytes_two = array_two.tobytes()

#print byte string
print(bytes_one)
print(bytes_two)

Code explanation

  • 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.

Output

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.

RELATED TAGS

python
RELATED COURSES

View all Courses

Keep Exploring