

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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.
- Related Questions & Answers
- For every set bit of a number toggle bits of other in C++
- Clear/Set a specific bit of a number in Arduino
- Python Program to Clear the Rightmost Set Bit of a Number
- Clear a bit in a BigInteger in Java
- How do you set cookies in the JSP?
- How do you create a list from a set in Java?
- How do you turn a list into a Set in Java?
- How do you turn an ArrayList into a Set in Java?
- set clear() in python
- How do you loop through a C# array?
- What to do if your classmates do not include you in their night outs just because you are a bit elder in age?
- How do you declare, initialize and access jagged arrays in C#?
- Position of rightmost set bit in C++
- How do you reverse a string in place in C or C++?
- How do you empty an array in C#?
Advertisements