【问题标题】:how to load 4-bit data into numpy array如何将 4 位数据加载到 numpy 数组中
【发布时间】:2014-10-14 20:15:52
【问题描述】:

我有一个包含 8 位复杂样本的二进制数据文件——即4 位和 4 位用于从 MSB 到 LSB 的虚数和实数(Q 和 I)分量。

如何将这些数据放入 numpy 复数数组中?

【问题讨论】:

    标签: python arrays numpy complex-numbers


    【解决方案1】:

    不支持处理 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 &lt;&lt; 4 &gt;&gt; 4imag = values &gt;&gt; 4 正确处理符号和类型。
    【解决方案2】:

    使用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
    

    【讨论】:

    • 所以没有办法用 memmap 或类似的东西来做?
    • 那么这样做不是更有效吗:real = np.bitwise_and(a, 0x0f); imag = np.bitwise_and(a &gt;&gt; 4, 0x0f); 其中a 是文件中的字节数组?
    • @B-Brock:是的,你的建议会更有效率。
    • @B-Brock 当然。我想要一个更具示范性的例子,而不是一些先进但快速的例子。但你绝对是对的。
    • 好的,谢谢你的意见!--这暗示了我想知道的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2020-11-27
    • 2014-10-18
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2019-09-14
    相关资源
    最近更新 更多