Python 如何解释numpy数组的二进制?

Python 如何解释numpy数组的二进制?,python,numpy,numpy-ndarray,Python,Numpy,Numpy Ndarray,描述PyArrayObject结构 在Python会话中,我有以下内容: >>> t_ar1 = np.linspace(0, 15, 16).reshape((4, 4)) >>> print(hex_fmt(string_at(id(t_ar1), 80).hex())) 0100000000000000 40b06eecbd7f0000 3053b973bf550000 02000000ffffffff 70eaa873bf550000 80eaa873

描述PyArrayObject结构

在Python会话中,我有以下内容:

>>> t_ar1 = np.linspace(0, 15, 16).reshape((4, 4))
>>> print(hex_fmt(string_at(id(t_ar1), 80).hex()))
0100000000000000
40b06eecbd7f0000
3053b973bf550000
02000000ffffffff
70eaa873bf550000
80eaa873bf550000
50c826adbd7f0000
00b66eecbd7f0000
01050000322c2033
0000000000000000
据我所知,第三行是指向数组实际数据的指针。查看那里的数据,我发现

>>> print(hex_fmt(string_at(id(0x55bf73b95330), 96).hex()))
0200000000000000
4049a801be7f0000
0200000000000000
3053b933fd560100
489601adbd7f0000
10ab27adbd7f0000
0000000000000000
0000000000000000
d09501adbd7f0000
b0aa27adbd7f0000
0000000000000000
0000000000000000
在这里,我希望在某处看到浮点数0.0-15.0。然而,我似乎找不到它们。这里发生了什么?

字符串\u来自ctypes模块

要直接从numpy数组获取数据,需要将通过string_at获得的字节字符串解释为8字节双精度浮点数数组。因此,我们需要使用struct module将字节字符串解释为数字数组:

from ctypes import string_at
import numpy as np
import struct # needed to unpack data

t_ar1 = np.linspace(0, 15, 16).reshape((4, 4))
struct.unpack('16d', string_at(t_ar1.__array_interface__['data'][0], size=8 * 16))
0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0, 13.0,14.0,15.0

应该是

string_at(0x55bf73b95330, 96)
而不是我所拥有的

string_at(id(0x55bf73b95330), 96)
在这种情况下,您将获得

>>> print(hex_fmt(string_at(0x55bf73b95330, 96).hex()))
0000000000000000
000000000000f03f
0000000000000040
0000000000000840
0000000000001040
0000000000001440
0000000000001840
0000000000001c40
0000000000002040
0000000000002240
0000000000002440
0000000000002640
正如所料

什么是十六进制fmt和字符串at?字符串at来自ctypes模块。hex_fmt只是漂亮地打印了hex,这并不重要。