C/C++ Algorithms

Bit Manipulation

Set, clear, toggle, and test individual flags.

What is Bit Manipulation?

Bit masks compactly represent independent boolean options inside an unsigned integer.

Important points

  • Test empty, single-element, duplicate, and already sorted inputs.
  • Separate correctness from optimization.
  • Use the standard library in production unless a custom implementation is justified.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>

int main(void) {
    unsigned flags = 0;
    flags |= 1u << 1;
    flags |= 1u << 3;
    flags ^= 1u << 1;
    printf("flags=%u bit3=%u\n", flags, (flags >> 3) & 1u);
}
Result of running the code
flags=8 bit3=1
C++
Run code →
main.cpp
#include <bitset>
#include <iostream>

int main() {
    std::bitset<4> flags;
    flags.set(1);
    flags.set(3);
    flags.flip(1);
    std::cout << "flags=" << flags
              << " bit3=" << flags.test(3) << '\n';
}
Result of running the code
flags=1000 bit3=1

C and C++ comparison

Use unsigned types for predictable shifts. C works directly with integer masks; C++ bitset provides named operations and readable binary output.

C

Loops, pointers, lengths, and temporary buffers are written explicitly.

C++

Iterators and standard algorithms separate operations from container representation.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Trace each comparison on paper.
  • Test duplicates and extreme values.
  • Benchmark the custom implementation against the standard library.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges