【发布时间】:2014-10-14 20:15:52
【问题描述】:
我有一个包含 8 位复杂样本的二进制数据文件——即4 位和 4 位用于从 MSB 到 LSB 的虚数和实数(Q 和 I)分量。
如何将这些数据放入 numpy 复数数组中?
【问题讨论】:
标签: python arrays numpy complex-numbers
我有一个包含 8 位复杂样本的二进制数据文件——即4 位和 4 位用于从 MSB 到 LSB 的虚数和实数(Q 和 I)分量。
如何将这些数据放入 numpy 复数数组中?
【问题讨论】:
标签: python arrays numpy complex-numbers
不支持处理 8 位复数(4 位实数,4 位虚数)。 因此,以下方法是一种有效地将它们读入单独的 numpy 数组以实现复数和虚数的好方法。
values = np.fromfile("filepath", dtype=int8)
real = np.bitwise_and(values, 0x0f)
imag = np.bitwise_and(values >> 4, 0x0f)
那么如果你想要一个复杂的数组,
signal = real + 1j * imag
这里有更多将两个实数数组转换为复数数组的方法:https://stackoverflow.com/a/2598820/1131073
如果值是可能为负数的 4 位整数(即应用二进制补码),您可以使用算术位移来正确分离两个通道:
real = (np.bitwise_and(values, 0x0f) << 4).astype(np.int8) >> 4
imag = np.bitwise_and(values, 0xf0).astype(int) >> 4
【讨论】:
bitwise_and 操作实际上是不必要的。 real = values << 4 >> 4 和 imag = values >> 4 正确处理符号和类型。
使用this answer 一次读取一个字节的数据,这应该可以工作:
with open("myfile", "rb") as f:
byte = f.read(1)
while byte != "":
# Do stuff with byte.
byte = f.read(1)
real = byte >> 4
imag = byte & 0xF
# Store numbers however you like
【讨论】:
real = np.bitwise_and(a, 0x0f); imag = np.bitwise_and(a >> 4, 0x0f); 其中a 是文件中的字节数组?