NumPy ndarray.tobytes()
The numpy.ndarray.tobytes()
method converts a NumPy array into a bytes object, containing its raw binary representation.
This is useful for serialization, file storage, or network transmission.
Syntax
ndarray.tobytes(order='C')
Parameters
Parameter | Type | Description |
---|---|---|
order | str, optional | Specifies the memory layout order for conversion. 'C' (row-major) and 'F' (column-major) are supported. Default is 'C' . |
Return Value
Returns a bytes
object containing the raw binary representation of the array data.
Examples
1. Converting a NumPy Array to Bytes
In this example, we convert a simple NumPy array to a bytes object.
import numpy as np
# Creating a NumPy array of integers
arr = np.array([1, 2, 3, 4], dtype=np.int32)
# Converting the array to bytes using default 'C' order
byte_data = arr.tobytes()
# Printing the byte representation
print(byte_data)
Output (may vary):
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'
The output is a byte string containing the binary representation of the integer values in little-endian format.
2. Converting a Multi-Dimensional Array to Bytes
This example demonstrates how a 2D NumPy array is converted into bytes.
import numpy as np
# Creating a 2D NumPy array
arr = np.array([[1, 2], [3, 4]], dtype=np.int32)
# Converting the array to bytes
byte_data = arr.tobytes()
# Printing the byte representation
print(byte_data)
Output (may vary):
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'
The bytes output represents the row-major (C-style) memory layout of the array.
3. Using Column-Major (‘F’) Order
Here, we specify column-major (‘F’) order when converting the array to bytes.
import numpy as np
# Creating a 2D NumPy array
arr = np.array([[1, 2], [3, 4]], dtype=np.int32)
# Converting the array to bytes using Fortran ('F') order
byte_data = arr.tobytes(order='F')
# Printing the byte representation
print(byte_data)
Output (may vary):
b'\x01\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00'
Unlike the default ‘C’ order, the elements are now stored column-wise in memory.
4. Writing and Reading an Array as Bytes
This example shows how to save the byte representation of an array to a file and restore it.
import numpy as np
# Creating a NumPy array
arr = np.array([5, 10, 15, 20], dtype=np.int32)
# Converting the array to bytes
byte_data = arr.tobytes()
# Writing the bytes to a file
with open('array_bytes.bin', 'wb') as f:
f.write(byte_data)
# Reading the bytes back from the file
with open('array_bytes.bin', 'rb') as f:
read_bytes = f.read()
# Converting the bytes back to a NumPy array
restored_arr = np.frombuffer(read_bytes, dtype=np.int32)
# Printing the restored array
print(restored_arr)
Output:
[ 5 10 15 20]
By writing and reading the byte representation, we can efficiently store and retrieve NumPy arrays while maintaining their original values.