首页 > 解决方案 > Numpy 将位打包成 32 位 little-endian 值

问题描述

Numpy 提供packbits函数将值转换为单个位。bitorder='little'我可以在 C 中将它们读取为 uint8_t 值而不会出现问题。但是,我想将它们读取为 uint32_t 值。这意味着我必须颠倒每 4 个字节的顺序。我试着用

import numpy as np

array = np.array([1,0,1,1,0,1,0,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,1,1,0,0,1,0,1,0,1, 
   1,0,0,1,1,0,1,0,1,1,0,0,1,1,1,0,0,1])
array = np.packbits(array, bitorder='little')
array.dtype = np.uint32
array.byteswap(inplace=True)

print(array)

但出现以下错误:

Traceback (most recent call last):
  File "sample.py", line 5, in <module>
    array.dtype = np.uint32
ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array.

我在输入中有 50 位。以 little-endian 格式写入的第一个 32 位块(最早的输入位是最低有效位)是0b10101001101011001101001010101101 = 2846675629,第二个是0b100111001101011001 = 160601. 所以预期的输出是

[2846675629 160601]

标签: pythonpython-3.xnumpybit-manipulationendianness

解决方案


您不能array.dtype = np.uint32像以前那样使用,因为 numpy 数组必须在内存中是连续的。

相反,您可以创建新类型的新数组。

import numpy as np

array = np.array([1,0,1,1,0,1,0,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,1,0,1,0,1,1,0,0,1,1,1,0,0,1])
array = np.packbits(array, bitorder='little')
array = np.array(array, dtype=np.uint32)
array.byteswap(inplace=True)

print(array)

推荐阅读