I want to use NumPy arrays to efficiently operate on large byte arrays. Unfortunately, assigning a bytes object to a slice of the NumPy array does not work as I would expect:
import struct
import numpy as np
array = np.zeros(10, dtype=np.uint8)
# Store 65535 into the first two bytes
array[0:2] = struct.pack('<H', 65535) # does not work
print(array)
This leads to the following exception:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
In this example, the bytes object results from a call to struct.pack. When wrapping the result into a bytearray, everything works as intended, but I think this will perform an unnecessary copy operation (which is not what I want):
array[0:2] = bytearray(struct.pack('<H', 65535)) # works
Why does a bytes object not work here? The fact that bytearray is mutable whereas bytes is not should not make a difference here.
I'm using NumPy version 1.16.4.