python位运算符_NumPy按位运算符解析和实例详解
本文概述
Numpy提供以下按位運算符。
SN
Operator
Description
1
bitwise_and
它用于計算相應數組元素之間的按位運算。
2
bitwise_or
它用于計算相應數組元素之間的按位運算。
3
invert
它用于計算按位而不是數組元素的運算。
4
left_shift
它用于將元素的二進制表示形式的位向左移動。
5
right_shift
它用于將元素的二進制表示形式的位向右移。
按位與運算
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
與(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
或(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
總結
以上是生活随笔為你收集整理的python位运算符_NumPy按位运算符解析和实例详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 70%进入体制内!2021年,清北毕业生
- 下一篇: 大离谱!论文“撞衫”,11篇不同高校论文