16

Is there any way to do a "reinterpret_cast" with numpy arrays? Here's an example:

>>> import numpy as np
>>> x=np.array([105,79,196,53,151,176,59,202,249,0,207,6], dtype=np.uint8)
>>> np.fromstring(x.tostring(),'<h')
array([ 20329,  13764, -20329, -13765,    249,   1743], dtype=int16)

I can call tostring() and then fromstring() to convert from an array to raw bytes and then back to another array. I'm just wondering if there's a way for me to skip the intermediate step. (not that it's a big deal, I would just like to understand.)

1 Answer 1

19

Yes. When you view an array with a different dtype, you are reinterpreting the underlying data (zeros and ones) according to the different dtype.

In [85]: x.view('<i2')
Out[85]: array([ 20329,  13764, -20329, -13765,    249,   1743], dtype=int16)
Sign up to request clarification or add additional context in comments.

Comments

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.