Is there an equivalent to numpy.array(someArray, dtype=numpy.uint16)
by just using the array
module in Python 3? I'm trying to build the equivalent of the buffer of a Javascript Uint16Array object: Uint16Array(someArray).buffer
).
Here's what I have so far:
import numpy as np
someArray = []
someArray.append(0)
someArray.append(216)
someArray.append(162)
someArray.append(52)
print(bytearray(np.array(someArray, dtype=np.uint16)))
Output: bytearray(b'\x00\x00\xd8\x00\xa2\x004\x00')
But, if I try the following:
import array as arrayModule
someArray = arrayModule.array("I", [])
someArray.append(0)
someArray.append(216)
someArray.append(162)
someArray.append(52)
print(bytearray(someArray.tobytes()))
Output: bytearray(b'\x00\x00\x00\x00\xd8\x00\x00\x00\xa2\x00\x00\x004\x00\x00\x00')
Using the numpy module works but I'd rather find a native way to accomplish the goal as this is the only place that I use numpy... seems inefficient to import a large module just to use it once.
You want to use "H" (unsigned short) instead of "I" (unsigned int). In C, int
can be 2 or 4 bytes depending on architecture and its usually 4. You could check someArray.itemsize
to verify on your machine.