📅  最后修改于: 2020-10-27 02:20:52             🧑  作者: Mango
Numpy提供以下按位运算运算符。
SN | Operator | Description |
---|---|---|
1 | bitwise_and | It is used to calculate the bitwise and operation between the corresponding array elements. |
2 | bitwise_or | It is used to calculate the bitwise or operation between the corresponding array elements. |
3 | invert | It is used to calculate the bitwise not the operation of the array elements. |
4 | left_shift | It is used to shift the bits of the binary representation of the elements to the left. |
5 | right_shift | It is used to shift the bits of the binary representation of the elements to the right. |
NumPy提供了bitwise_and()函数,该函数用于计算两个操作数的bitwise_and运算。
对操作数的二进制表示形式的相应位执行按位与运算。如果操作数中的两个对应位都设置为1,则仅AND结果中的结果位将设置为1,否则将设置为0。
import numpy as np
a = 10
b = 12
print("binary representation of a:",bin(a))
print("binary representation of b:",bin(b))
print("Bitwise-and of a and b: ",np.bitwise_and(a,b))
输出:
binary representation of a: 0b1010
binary representation of b: 0b1100
Bitwise-and of a and b: 8
当且仅当两个位均为1时,两个位的AND结果的输出为1,否则为0。
A | B | AND (A, B) |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
NumPy提供了bitwise_or()函数,该函数用于计算两个操作数的按位或运算。
对操作数的二进制表示形式的相应位执行按位或运算。如果操作数中的相应位之一设置为1,则OR结果中的结果位将设置为1;否则,结果为1。否则它将设置为0。
import numpy as np
a = 50
b = 90
print("binary representation of a:",bin(a))
print("binary representation of b:",bin(b))
print("Bitwise-or of a and b: ",np.bitwise_or(a,b))
输出:
binary representation of a: 0b110010
binary representation of b: 0b1011010
Bitwise-or of a and b: 122
如果一位中的一位为1,则两位的或结果的输出为1,否则为0。
A | B | Or (A, B) |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
它用于计算按位而不是给定操作数的运算。如果在函数传递有符号整数,则返回2的补码。
考虑以下示例。
import numpy as np
arr = np.array([20],dtype = np.uint8)
print("Binary representation:",np.binary_repr(20,8))
print(np.invert(arr))
print("Binary representation: ", np.binary_repr(235,8))
输出:
Binary representation: 00010100
[235]
Binary representation: 11101011
它将操作数的二进制表示形式的位向左移动指定位置。从右边追加相等数量的0。考虑以下示例。
import numpy as np
print("left shift of 20 by 3 bits",np.left_shift(20, 3))
print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))
输出:
left shift of 20 by 3 bits 160
Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000
它将操作数二进制表示形式的位向右移动指定位置。从左侧追加相等数量的0。考虑以下示例。
import numpy as np
print("left shift of 20 by 3 bits",np.right_shift(20, 3))
print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))
输出:
left shift of 20 by 3 bits 2
Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000