2

在 Numpy 中,我需要将一些二进制数据解压缩到一个变量中。过去,我一直在使用 Numpy 中的“fromstring”函数对其进行解包并提取第一个元素。有没有办法可以直接将二进制数据解压缩为 Numpy 类型,并避免创建我几乎忽略的 Numpy 数组的开销?

这就是我目前所做的:

>>> int_type
dtype('uint32')
>>> bin_data = '\x1a\x2b\x3c\x4d'
>>> value = numpy.fromstring(bin_data, dtype = int_type)[0]
>>> print type(value), value
<type 'numpy.uint32'> 1295788826

我想做这样的事情:

>>> value = int_type.fromstring(bin_data)
>>> print type(value), value
<type 'numpy.uint32'> 1295788826
4

2 回答 2

2
>>> np.frombuffer(bin_data, dtype=np.uint32)
array([1295788826], dtype=uint32)

虽然这会创建一个数组结构,但实际数据在字符串和数组之间共享:

>>> x = np.frombuffer(bin_data, dtype=np.uint32)
>>> x[0] = 1
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
RuntimeError: array is not writeable

fromstring会复制它。

于 2012-11-19T10:23:15.557 回答
2
In [16]: import struct

In [17]: bin_data = '\x1a\x2b\x3c\x4d'

In [18]: value, = struct.unpack('<I', bin_data)

In [19]: value
Out[19]: 1295788826
于 2012-11-19T10:13:47.670 回答