How do eight Boolean flags fit in a byte?
packbits packs binary flags into unsigned bytes. Bit order determines whether the first flag occupies the high or low bit.
numpy.packbits in practice
With the high bit first, two leading ones and six zeros encode 192. The last byte is zero-padded for incomplete groups, so store the original flag count.
import numpy as np
np.packbits([1,1,0,0,0,0,0,0],bitorder='big')Result [192]
中文
八个布尔状态怎样装进一个字节?
packbits 把二值标记压入 uint8,bitorder 指定第一个标记放在高位还是低位。
numpy.packbits 算例
采用高位优先,开头两位为一其余为零,结果是 192。标记数不是八的倍数时末字节会补零,解码要保留原长度。
import numpy as np
np.packbits([1,1,0,0,0,0,0,0],bitorder='big')结果 [192]