How can I make a numpy ndarray from bytes?

To deserialize the bytes you need np.frombuffer().
tobytes() serializes the array into bytes and the np.frombuffer() deserializes them.

Bear in mind that once serialized, the shape info is lost, which means that after deserialization, it is required to reshape it back to its original shape.

Below is a complete example:

import numpy as np

x = np.array([[0, 1], [2, 3]], np.int8)
bytes = x.tobytes()
# bytes is a raw array, which means it contains no info regarding the shape of x
# let's make sure: we have 4 values with datatype=int8 (one byte per array's item), therefore the length of bytes should be 4bytes
assert len(bytes) == 4, "Ha??? Weird machine..."

deserialized_bytes = np.frombuffer(bytes, dtype=np.int8)
deserialized_x = np.reshape(deserialized_bytes, newshape=(2, 2))
assert np.array_equal(x, deserialized_x), "Deserialization failed..."

Leave a Comment