如何在 C/C++ 中設定、清除和切換一個位?
在 C、C++、Python 和所有其他支援這些操作的程式語言中,可以使用位運算子設定、清除和切換位。還需要使用移位運算子將位移到正確的位置。
設定位
要設定位,我們需要使用位或運算子 -
示例
#include<iostream> using namespace std; int main() { int i = 0, n; // Enter bit to be set: cin >> n; i |= (1 << n); // Take OR of i and 1 shifted n positions cout << i; return 0; }
輸出
如果輸入 4,這將給出輸出 -
16
因為 16 在二進位制中等於 10000。
清除位
要清除一位,我們需要使用位與運算子 (&) 和位非運算子 (~) -
示例
#include<iostream> using namespace std; int main() { // i is 110 in binary int i = 6, n; // Enter bit to be cleared: cin >> n; i &= ~(1 << n); // Take OR of i and 1 shifted n positions negated cout << i; return 0; }
輸出
如果輸入 1,這將給出輸出 -
4
因為 110 變為 100,在十進位制中等於 4。
切換位
要切換一位,我們需要使用位異或運算子 (^) -
示例
#include<iostream> using namespace std; int main() { // i is 110 in binary int i = 6, n; // Enter bit to be toggled: cin >> n; i ^= (1 << n); // Take XOR of i and 1 shifted n positions cout << i; return 0; }
輸出
如果輸入 1,這將給出輸出 -
4
因為 110 變為 100,在十進位制中等於 4。
廣告