0

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

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. Yes, using "H" did the trick. So is there a way that I can force the use of 2 bytes, regardless of machine architecture? I'm under the impression that numpy.array(someArray, dtype=numpy.uint16) forces the use of 2 bytes.
I can't think of a way. "H" is implemented by the C 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.
Now I'm curious how numpy does it. it would be a nice addition to array.
Yes, logging this potential scenario would def be useful. Regarding 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.