How can a status mask report the number of enabled flags?

bitwise_count counts ones in the binary representation of the absolute integer value. With unsigned masks this directly counts set flags.

numpy.bitwise_count in practice

Mask thirteen is binary 1101 and enables three flags. Use unsigned values for a fixed-width protocol where the top bit denotes a flag of its own.

import numpy as np
np.bitwise_count(np.array([0,7,13],dtype=np.uint8))

Result [0, 3, 3]

中文

怎样从状态掩码统计启用标记数?

bitwise_count 统计整数绝对值二进制表示中的一位数,对无符号掩码可直接得到启用位数。

numpy.bitwise_count 算例

掩码 13 的二进制为 1101,有三个标记。若协议按固定宽度把最高位当普通标记,应选无符号类型解释原始字节。

import numpy as np
np.bitwise_count(np.array([0,7,13],dtype=np.uint8))

结果 [0, 3, 3]

References / 参考来源

Keep reading / 继续阅读