2012-11-19 53 views
2

在Numpy中,我需要將一些二進制數據解壓縮爲一個變量。在過去,我一直使用Numpy中的'fromstring'函數解壓它,並提取第一個元素。有沒有一種方法可以直接將二進制數據解壓縮爲Numpy類型,並避免創建一個我幾乎忽略的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 

回答

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 
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會複製它。

+0

有趣的是,thx – Qlaus