
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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 create a list from a set in Java?
- How do you turn a list into a Set in Java?
- How do I clear the cin buffer in C++?
- How do you set cookies in the JSP?
- How do you turn an ArrayList into a Set in Java?
- Position of rightmost set bit in C++
- set clear() in python
- Find most significant set bit of a number in C++
- What to do if your classmates do not include you in their night outs just because you are a bit elder in age?
- Set a bit for BigInteger in Java
- Position of the K-th set bit in a number in C++

Advertisements