- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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; }
Output
If you enter 4, This will give the output −
16
because 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
#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; }
Output
If you enter 1, This will give the output −
4
because 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
#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; }
Output
If you enter 1, This will give the output −
4
because 110 becomes 100 which is equivalent to 4 in decimal.
Advertisements