Numpy 将二进制字符串解压缩为单个变量



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

这是我目前所做的:

>>> int_type
dtype('uint32')
>>> bin_data = 'x1ax2bx3cx4d'
>>> 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
In [16]: import struct
In [17]: bin_data = 'x1ax2bx3cx4d'
In [18]: value, = struct.unpack('<I', bin_data)
In [19]: value
Out[19]: 1295788826
>>> 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会复制它。

最新更新