Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Check and Set Bits in C++

Check, set, clear, and toggle a single bit in C++ using masks built with 1 << pos and the &, |, and ^ operators. Step-by-step on the number 12 with binary output.

BeginnerBitwise Operations ProgramsExample 2 of 5
check-and-set-bits.cpp
1#include <iostream>
2#include <bitset>
3using namespace std;
4
5bool isBitSet(int num, int pos) {
6 return (num & (1 << pos)) != 0;
7}
8
9int setBit(int num, int pos) {
10 return num | (1 << pos);
11}
12
13int clearBit(int num, int pos) {
14 return num & ~(1 << pos);
15}
16
17int toggleBit(int num, int pos) {
18 return num ^ (1 << pos);
19}
20
21int main() {
22 int num = 12; // 00001100
23
24 cout << "Original number: " << bitset<8>(num) << " (" << num << ")" << endl;
25
26 // Check bits
27 cout << "\nChecking bits:" << endl;
28 for (int i = 0; i < 8; i++) {
29 cout << "Bit " << i << ": " << (isBitSet(num, i) ? "SET" : "CLEAR") << endl;
30 }
31
32 // Set bit 0
33 num = setBit(num, 0);
34 cout << "\nAfter setting bit 0: " << bitset<8>(num) << " (" << num << ")" << endl;
35
36 // Clear bit 2
37 num = clearBit(num, 2);
38 cout << "After clearing bit 2: " << bitset<8>(num) << " (" << num << ")" << endl;
39
40 // Toggle bit 3
41 num = toggleBit(num, 3);
42 cout << "After toggling bit 3: " << bitset<8>(num) << " (" << num << ")" << endl;
43
44 return 0;
45}

Sample Output

Bit 2: SET

12 has a 1 at position 2.

After toggling bit 3: 00000001 (1)

Bit 3 of 9 flipped off.

In this one

  • How 1 << pos builds a one-bit mask
  • How & checks a bit
  • How | sets, & ~ clears, and ^ toggles
  • Which bit positions are safe

How it works

  1. 1

    num = 12 (00001100).

  2. 2

    Check bits 0 to 7: 2 and 3 are SET.

  3. 3

    setBit(0) → 13.

  4. 4

    clearBit(2) → 9.

  5. 5

    toggleBit(3) → 1.

Dry run: Check and Set Bits

13 = 00001101

  1. 1.~(1 << 2) = 11111011
  2. 2.13 & 11111011 = 00001001 = 9
13 = 00001101
~(1 << 2) = 11111011
13 & 11111011 = 00001001 = 9

Edge cases

Setting a bit that is already set

setBit(12, 2)

12 is unchanged, because OR with a 1 that is already there changes nothing.

Position 31 or more

isBitSet(num, 35)

1 << 35 is undefined for int. Use 1ULL << pos with a 64-bit type.

What's going on

Four tiny functions cover almost every single-bit job: check, set, clear, and toggle. All of them start from a mask, 1 << pos, which is a number with just one 1 at position pos. Bit 0 is the rightmost.

isBitSet ANDs the number with the mask. If that bit is 1 the result is non-zero; otherwise it is 0. For 12 (00001100), bits 2 and 3 are SET and the rest are CLEAR, which is what the loop prints.

setBit ORs with the mask, which forces that bit to 1 and leaves the others alone. Setting bit 0 turns 12 into 00001101 = 13.

clearBit ANDs with ~(1 << pos), a mask that has every bit set except pos. That forces one bit to 0. Clearing bit 2 of 13 gives 00001001 = 9.

toggleBit XORs with the mask, which flips that one bit. Toggling bit 3 of 9 turns it off, giving 00000001 = 1. Toggling it again would turn it back on.

These are the building blocks for storing many yes/no flags in one integer. For example, file permissions use one bit each for read, write, and execute.

pos must be from 0 to 30 for a 32-bit int. 1 << 31 lands on the sign bit and gives a negative number, and 32 or more is undefined. Use 1u << pos or 1ULL << pos for higher bits.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <bitset> is there because it provides bitset for binary representation display. Leave one out and the compiler stops at the first name it does not recognize.

Understanding Bit Manipulation

Bit Position Concept:

Bits numbered from right (0-indexed)
Position 0: rightmost bit (LSB)
Position n-1: leftmost bit (MSB)
Each position represents 2^position

Common Operations:

Check: is bit set?
Set: make bit 1
Clear: make bit 0
Toggle: flip bit value

Checking if Bit is Set

Operation:

bool isBitSet(int num, int pos) {

return (num & (1 << pos)) != 0;

}

What happens here:

1 << pos: creates mask with bit at position pos set
num & mask: extracts bit at position
!= 0: checks if bit is set
Returns true if bit is 1

Example:

num = 12 (00001100), pos = 2
1 << 2 = 4 (00000100)
12 & 4 = 4 (bit 2 is set)

Setting a Bit

Operation:

int setBit(int num, int pos) {

return num | (1 << pos);

}

What happens here:

1 << pos: creates mask with bit at position pos
num | mask: sets bit at position
OR operation sets bit to 1
Other bits unchanged

Example:

num = 12 (00001100), pos = 0
1 << 0 = 1 (00000001)
12 | 1 = 13 (00001101)

Clearing a Bit

Operation:

int clearBit(int num, int pos) {

return num & ~(1 << pos);

}

What happens here:

1 << pos: creates mask with bit at position pos
~mask: inverts mask (all 1s except position pos)
num & ~mask: clears bit at position
AND operation clears bit to 0

Example:

num = 12 (00001100), pos = 2
1 << 2 = 4 (00000100)
~4 = 251 (11111011)
12 & 251 = 8 (00001000)

Toggling a Bit

Operation:

int toggleBit(int num, int pos) {

return num ^ (1 << pos);

}

What happens here:

1 << pos: creates mask with bit at position pos
num ^ mask: flips bit at position
XOR operation toggles bit
0 becomes 1, 1 becomes 0

Example:

num = 12 (00001100), pos = 3
1 << 3 = 8 (00001000)
12 ^ 8 = 4 (00000100)

When to Use Bit Manipulation

Good fits:

Flags and permissions
Efficient data structures
Memory optimization
System programming
Performance-critical code

Example Scenarios:

File permissions (read, write, execute)
Feature flags
State machines
Bit arrays
Compression algorithms

Important Considerations

Bit Position:

Usually 0-indexed from right
Position 0: least significant bit
Be careful with position values
Validate position range

Efficiency:

Very fast operations
Single CPU instruction
No loops needed
Optimal performance

Readability:

Can be less readable
Document operations
Use helper functions
Clear variable names

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which expression clears bit 4 of x?

Pick an answer to check it.

Question 2

Toggling bit 0 of 6 gives what?

Pick an answer to check it.

Questions people ask

How do I check if a number is odd with bits?

(n & 1) != 0.

How do I clear the lowest set bit?

n & (n - 1).

Is there a library type for this?

std::bitset has set(), reset(), flip(), and test().