2014-09-24 96 views
2

我有一個由NumPy創建的二進制矩陣。矩陣有5行32列。將二進制字符串轉換爲IEEE-754單精度 - Python

array([[1, 1, ..., 1, 1], 
    [0, 1, ..., 0, 1], 
    [1, 1, ..., 0, 1], 
    [0, 0, ..., 1, 0], 
    [1, 1, ..., 0, 1]]) 

我把一個矩陣行轉換成一個字符串,然後整數。

str = ''.join(map(str,array[0])).replace(' ','') 
int(str, base=2) 

如何將字符串轉換爲float(float32 - IEEE-754 single)?

回答

4

使用struct.packstruct.unpack

>>> a = [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 
...  1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1] 
>>> i = int(''.join(map(str, a)), 2) 
>>> import struct 
>>> struct.unpack('f', struct.pack('I', i))[0] 
1.100000023841858 

import struct 

matrix = array(...) 

st_i = struct.Struct('I') 
st_f = struct.Struct('f') 
float_values = [ 
    st_f.unpack(st_i.pack(int(''.join(map(str, a)), 2))) 
    for a in matrix 
] 

注:根據陣列的字節順序,你所需要的結構格式之前預先考慮<>

順便說一句,覆蓋str不是一個好主意。賦值後不能使用str函數/類型。

1

這是一種令人費解的,但你可以得到相同的結果作爲您的原始代碼在一個單一的襯墊爲:

In [61]: a = np.random.randint(2, size=(5, 32)) 

In [62]: for x in a: 
    ....:    x_t = ''.join(map(str, x)) 
    ....:    print x_t, int(x_t, 2) 
    ....: 
11111111100000111010110110101100 4286819756 
01001000110000111001000100011110 1220776222 
10101111100100010000111010100111 2945519271 
01101111101100011111101001100110 1873934950 
11001000110101000111010100000011 3369366787 

In [63]: np.packbits(a.reshape(-1, 8)).reshape(-1, 4)[:, ::-1].copy().view(np.uint32) 
Out[63]: 
array([[4286819756], 
     [1220776222], 
     [2945519271], 
     [1873934950], 
     [3369366787]], dtype=uint32) 
相關問題