Bitwise Operations Programs
C++ bitwise operator programs: AND, OR, XOR, NOT, and shifts, checking and setting bits, counting set bits, XOR swap, and finding missing numbers with XOR.
5 programs · open one, then the next
Start with Basic Bitwise Operations- 01Basic Bitwise OperationsBeginnerC++ bitwise operators with binary output: AND, OR, XOR, NOT, left and right shift on 12 and 25, and why ~12 prints as -13 in two's complement.Open example →cpp#include <iostream> #include <bitset> using namespace std;
- 02Check and Set BitsBeginnerCheck, 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.Open example →cpp#include <iostream> #include <bitset> using namespace std;
- 03Count Set BitsIntermediateCount set bits in C++ three ways: a shift loop, Brian Kernighan's n & (n − 1) trick, and __builtin_popcount, with why negative numbers loop forever.Open example →cpp#include <iostream> #include <bitset> using namespace std;
- 04Swap using XORIntermediateSwap two numbers with XOR in C++ and no temporary variable: why the three XOR steps work, rotating three values, and the same-variable trap that zeroes it.Open example →cpp#include <iostream> using namespace std; void swapXOR(int& a, int& b) {
- 05Find Missing Number using XORAdvancedFind a missing number with XOR in C++: XOR 1 to n against the array so pairs cancel, then find two missing numbers by splitting on the lowest set bit.Open example →cpp#include <iostream> #include <vector> using namespace std;