lundi 19 mai 2014

python - conversion de numpy tableau d'un type à un autre en ré-interprétant les octets bruts - Stack Overflow


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.)




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)


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.)



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)

0 commentaires:

Enregistrer un commentaire