python - 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]
解决方案
您不能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)
推荐阅读
- php - 何时使用 bcadd 与正常添加浮点数
- azure-devops - 将构建和发布管道从一个组织转移到另一个组织
- testing - 需要在 cypress 中模拟 POST 请求
- html - 将内容(链接/图像)添加到引导程序 4 弹出窗口中
- android - CameraX图像分析的imageproxy大小和PreviewView大小不一样
- python - Django:TemplateSyntaxError:无法解析剩余部分(扩展标签)
- python - 有没有办法在 kv 文件中指定 Kivy 不在启动时呈现小部件?
- r - 在R中转换一个数据框,根据一个变量重新组织
- python - 删除 json 中的数据集
- html - TypeScript:渲染参数