下面是 NumPy
包中可用的位操作函数。
函数 | 操作及描述 |
---|---|
bitwise_and | 对数组元素执行位与操作 |
bitwise_or | 对数组元素执行位或操作 |
invert | 计算位非 |
left_shift | 向左移动二进制表示的位 |
right_shift | 向右移动二进制表示的位 |
bitwise_and
通过np.bitwise_and()
函数对输入数组中的整数的二进制表示的相应位执行位与
运算。
例子
>>> import numpy as np
>>> a, b = 13, 17
>>> bin(a), bin(b)
('0b1101', '0b10001')
>>> np.bitwise_and(13, 17)
1
你可以使用下表验证此输出。 考虑下面的位与真值表。
1 | 1 | 0 | 1 | ||
---|---|---|---|---|---|
AND | |||||
1 | 0 | 0 | 0 | 1 | |
result | 0 | 0 | 0 | 0 | 1 |
bitwise_or
通过np.bitwise_or()
函数对输入数组中的整数的二进制表示的相应位执行位或
运算。
例子
>>> import numpy as np
>>> a, b = 13, 17
>>> bin(a), bin(b)
('0b1101', '0b10001')
>>> np.bitwise_or(13, 17)
29
你可以使用下表验证此输出。 考虑下面的位或真值表。
1 | 1 | 0 | 1 | ||
---|---|---|---|---|---|
OR | |||||
1 | 0 | 0 | 0 | 1 | |
result | 1 | 1 | 1 | 0 | 1 |
invert
此函数计算输入数组中整数的位非结果。 对于有符号整数,返回补码
。
例子
>>> np.invert(np.array([13], dtype=np.uint8))
array([242], dtype=uint8)
>>> np.binary_repr(13, width=8)
'00001101'
>>> np.binary_repr(242, width=8)
'11110010'
请注意,np.binary_repr()
函数返回给定宽度中十进制数的二进制表示。
left_shift
numpy.left shift()
函数将数组元素的二进制表示中的位向左移动到指定位置,右侧附加相等数量的 0
。
例如,
>>> np.left_shift(10, 2)
40
>>> np.binary_repr(10, width=8)
'00001010'
>>> np.binary_repr(40, width=8)
'00101000'
right_shift
numpy.right_shift()
函数将数组元素的二进制表示中的位向右移动到指定位置,左侧附加相等数量的 0
。
>>> np.right_shift(40, 2)
10
>>> np.binary_repr(40, width=8)
'00101000'
>>> np.binary_repr(10, width=8)
'00001010'