NumPy(四): 位运算

NumPy "bitwise_" 开头的函数是位运算函数。

注:也可以使用 "&"、 "~"、 "|" 和 "^" 等操作符进行计算。

bitwise_and() 函数对数组中整数的二进制形式执行位与运算。

>>> import numpy as np 
>>> a,b = 13,17
#13与17的二进制
>>> print (bin(a), bin(b))
0b1101 0b10001
#位与
>>> print (np.bitwise_and(13, 17))
1


>>> print(int("00001",2))
1
>>> 

以上实例可以用下表来说明:

    1 1 0 1
AND
  1 0 0 0 1
运算结果 0 0 0 0 1

位与操作运算规律如下:

A B AND
1 1 1
1 0 0
0 1 0
0 0 0

bitwise_or()函数对数组中整数的二进制形式执行位或运算

>>> print (bin(a), bin(b))
0b1101 0b10001
>>> print (np.bitwise_or(13, 17))
29 
>>> print(int("11101",2))
29

以上实例可以用下表来说明:

    1 1 0 1
OR
  1 0 0 0 1
运算结果 1 1 1 0 1

位或操作运算规律如下:

A B OR
1 1 1
1 0 1
0 1 1
0 0 0

 invert() 函数对数组中整数进行位取反运算,即 0 变成 1,1 变成 0。

>>> print (np.invert(np.array([13], dtype = np.uint8)))
[242]

#13 的二进制表示:
>>> print (np.binary_repr(13, width = 8))
00001101

#242 的二进制表示:
>>> print (np.binary_repr(242, width = 8))
11110010

left_shift() 函数将数组元素的二进制形式向左移动到指定位置,右侧附加相等数量的 0。

#将10向左挪两位
>>> print (np.left_shift(10,2))
40

#10的二进制代码
>>> print (np.binary_repr(10, width = 8))
00001010

#40的二进制代码
>>> print (np.binary_repr(40, width = 8))
00101000

right_shift() 函数将数组元素的二进制形式向右移动到指定位置,左侧附加相等数量的 0。

>>> print (np.right_shift(40,2))
10

猜你喜欢

转载自blog.csdn.net/zcb_data/article/details/110097095