Pack the elements of a binary-valued Numpy array into bits in a uint8 array

numpyserver side programmingprogramming更新于 2025/8/13 13:07:17

To pack the elements of a binary-valued array into bits in a uint8 array, use the numpy.packbits() method in Python Numpy. The result is padded to full bytes by inserting zero bits at the end.

The axis is the dimension over which bit-packing is done. None implies packing the flattened array. The bitorder is the order of the input bits. 'big' will mimic bin(val), [0, 0, 0, 0, 0, 0, 1, 1] ⇒ 3 = 0b00000011, 'little' will reverse the order so [1, 1, 0, 0, 0, 0, 0, 0] ⇒ 3. Defaults to 'big'.

The function packbits() returns the array of type uint8 whose elements represent bits corresponding to the logical (0 or nonzero) value of the input elements. The shape of packed has the same number of dimensions as the input.

步骤

首先,导入所需的库 −

import numpy as np

Create a 3d array −

arr = np.array([[ [1,0,1],[0,1,0]],[[1,1,0],[0,0,1]],[[1, 1, 0],[0, 0, 1] ]])

显示我们的数组 −

print("数组...
",arr)

获取数据类型 −

print("
数组数据类型...
",arr.dtype)

获取数组的维度 −

print("
数组维度...
",arr.ndim)

获取数组的形状 −

print("
我们的数组形状...
",arr.shape)

获取数组元素的数量 −

print("
数组中的元素...
",arr.size)

要将二进制数组的元素打包成 uint8 数组中的位,请使用 Python Numpy 中的 numpy.packbits() 方法。结果会在末尾插入零位,以填充为完整字节。 −

res = np.packbits(arr)
print("
结果...
",res)

示例

import numpy as np

# 创建一个三维数组
arr = np.array([[ [1,0,1], [0,1,0]],[ [1,1,0],[0,0,1]],[ [1, 1, 0],[0, 0, 1] ]])

# 显示数组
print("数组...
",arr) # 获取数据类型 print("
数组数据类型...
",arr.dtype) # 获取数组的维度 print("
数组维度...
",arr.ndim) # 获取数组的形状 print("
我们的数组形状...
",arr.shape) # 获取数组元素的数量 print("
数组中的元素...
",arr.size) # 要将二进制数组的元素打包成 uint8 数组的位,请使用 Python Numpy 中的 numpy.packbits() 方法 # 通过在末尾插入零位来填充结果至完整字节 res = np.packbits(arr) print("
结果...
",res)

输出

python3 main.py
数组...
[[[1 0 1]
[0 1 0]]

[[1 1 0]
[0 0 1]]

[[1 1 0]
[0 0 1]]]

数组数据类型...
int64

数组维度...
3

我们的数组形状...
(3, 2, 3)

数组中的元素...
18

结果...
[171 28 64]

相关文章