Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do you set, clear, and toggle a bit in C/C++?
You can set clear and toggle bits using bitwise operators in C, C++, Python, and all other programming languages that support these operations. You also need to use the bitshift operator to get the bit to the right place.
Setting a bit
To set a bit, we'll need to use the bitwise OR operator −
Example
#includeusing namespace std; int main() { int i = 0, n; // Enter bit to be set: cin >> n; i |= (1 Output
If you enter 4, This will give the output −
16because 16 is equivalent to 10000 in binary.
Clearing a bit
To clear a bit, we'll need to use the bitwise AND operator(&) and bitwise NOT operator(~) −
Example
#includeusing namespace std; int main() { // i is 110 in binary int i = 6, n; // Enter bit to be cleared: cin >> n; i &= ~(1 Output
If you enter 1, This will give the output −
4because 110 becomes 100 which is equivalent to 4 in decimal.
Toggling a bit
To toggle a bit, we'll need to use the bitwise XOR operator(^) −
Example
#includeusing namespace std; int main() { // i is 110 in binary int i = 6, n; // Enter bit to be toggled: cin >> n; i ^= (1 Output
If you enter 1, This will give the output −
4because 110 becomes 100 which is equivalent to 4 in decimal.
