Check and Set Bits
Check if Bit is Set and Set/Clear Bits in C++
BeginnerTopic: Bitwise Operations Programs
C++ Check and Set Bits Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <bitset>
using namespace std;
bool isBitSet(int num, int pos) {
return (num & (1 << pos)) != 0;
}
int setBit(int num, int pos) {
return num | (1 << pos);
}
int clearBit(int num, int pos) {
return num & ~(1 << pos);
}
int toggleBit(int num, int pos) {
return num ^ (1 << pos);
}
int main() {
int num = 12; // 00001100
cout << "Original number: " << bitset<8>(num) << " (" << num << ")" << endl;
// Check bits
cout << "\nChecking bits:" << endl;
for (int i = 0; i < 8; i++) {
cout << "Bit " << i << ": " << (isBitSet(num, i) ? "SET" : "CLEAR") << endl;
}
// Set bit 0
num = setBit(num, 0);
cout << "\nAfter setting bit 0: " << bitset<8>(num) << " (" << num << ")" << endl;
// Clear bit 2
num = clearBit(num, 2);
cout << "After clearing bit 2: " << bitset<8>(num) << " (" << num << ")" << endl;
// Toggle bit 3
num = toggleBit(num, 3);
cout << "After toggling bit 3: " << bitset<8>(num) << " (" << num << ")" << endl;
return 0;
}Output
Original number: 00001100 (12) Checking bits: Bit 0: CLEAR Bit 1: CLEAR Bit 2: SET Bit 3: SET Bit 4: CLEAR Bit 5: CLEAR Bit 6: CLEAR Bit 7: CLEAR After setting bit 0: 00001101 (13) After clearing bit 2: 00001001 (9) After toggling bit 3: 00000001 (1)
Understanding Check and Set Bits
Check bit: num & (1 << pos). Set bit: num | (1 << pos). Clear bit: num & ~(1 << pos). Toggle bit: num ^ (1 << pos). These operations are fundamental for bit manipulation. Used in flags, permissions, and efficient data structures.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.