将二进制文件读取为复数数组

时间:2019-07-17 19:47:56

标签: python python-3.x numpy

我有一个写为

的二进制文件
int push(int &tos, int x)
{
    // Any changes to tos are now reflected in the variable passed in.
    ...
}

我需要将其转换为一维复数数组。无法弄清楚如何将“元组或列表”组合为单个值

16b-Real (little endian, 2s compliment)
16b-Imag (little endian, 2s compliment)
.....repeating

输出:

import numpy as np
dtype = np.dtype([('i','<i2'), ('q','<i2')])
array = np.fromfile(data_file, dtype=dtype)
print(array)
el = array[0]
print(el)
print(type(el))

希望输出:

[(531, -660) (267, -801) (-36, -841) ... (835, -102) (750, -396)
 (567, -628)]
(531, -660)
<class 'numpy.void'>

2 个答案:

答案 0 :(得分:3)

您可以在遍历元组列表时将每个元组转换为一个complex数字

array = [(531, -660), (267, -801), (-36, -841) ,(835, -102) ,(750, -396), (567, -628)]

#Iterate over each element and convert it to complex
array = [complex(*item) for item in array]

print(array)
print(type(array[0]))

输出将为

[(531-660j), (267-801j), (-36-841j), (835-102j), (750-396j), (567-628j)]
<class 'complex'>

答案 1 :(得分:1)

因此,您已将文件加载为具有2个整数字段的结构化数组:

In [71]: dtype = np.dtype([('i','<i2'), ('q','<i2')])                                                        
In [72]: arr = np.array([(531, -660), (267, -801), (-36, -841), (835, -102), (750, -396)], dtype)            
In [73]: arr                                                                                                 
Out[73]: 
array([(531, -660), (267, -801), (-36, -841), (835, -102), (750, -396)],
      dtype=[('i', '<i2'), ('q', '<i2')])

我们可以将两个字段与适当的1j乘数相加,以组成一个复杂的数组:

In [74]: x=arr['i']+1j*arr['q']                                                                              
In [75]: x                                                                                                   
Out[75]: array([531.-660.j, 267.-801.j, -36.-841.j, 835.-102.j, 750.-396.j])

如果我没记错的话,numpy仅实现浮点复数(64位和128位),因此很可能已经过了<i2这个阶段。