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.
1 Answer 1
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.
4 Comments
numpy.array(someArray, dtype=numpy.uint16) forces the use of 2 bytes.sizeof(short). C only sets relative sizes for these things. Its 2 bytes in most architectures, but not guaranteed. In the "uint16" world, there are architecture dependent header files that map uint16 correctly or bomb out the compile of the product (numpy in this case). You could assert arrayModule.array("H").itemsize == 2, "2 byte short not supported on this architecture". I doubt you'll ever run into a case where it actually does assert.numpy.uint16, I'm not 100% certain that numpty forces the 2 byte size either... it's just that the spec for using "H" (unsigned short) lists 2 bytes at the 'minimum' size in bytes: docs.python.org/3/library/array.html Explore related questions
See similar questions with these tags.