← Back to C++ Course | Chapter 3: Operators | Lesson 5 of 9

C++ Bitwise Operators

Bitwise AND and OR

Bitwise & and | operate on the individual binary digits of a number rather than its value as a whole: & sets each output bit to 1 only where both operands have a 1 in that position, while | sets it to 1 if either operand does. These are commonly used to check or combine flags packed into a single integer, one bit per flag.

Example: Bitwise AND and OR

cpp
#include <iostream>

int main() {
	int a = 6, b = 3; // 110 and 011
	std::cout << (a & b) << std::endl; // 010 = 2
	std::cout << (a | b) << std::endl; // 111 = 7
	return 0;
}

Bitwise XOR

Bitwise ^ (XOR) sets each output bit to 1 exactly where the two operands' bits differ, and to 0 where they match. A distinctive property of XOR is that applying it twice with the same value undoes the first application, which is the basis of some simple encryption and value-swapping tricks.

Example: Bitwise XOR

cpp
#include <iostream>

int main() {
	int a = 5, b = 3;
	int x = a ^ b;
	std::cout << x << std::endl;
	std::cout << (x ^ b) << std::endl; // XOR twice undoes it: back to a
	return 0;
}

Bitwise NOT

Bitwise ~ (NOT) is a unary operator that flips every bit of its operand, turning every 1 into a 0 and every 0 into a 1 — this is also called the one's complement. It's frequently used to build a bitmask that clears specific bits when combined with &, since ~mask inverts exactly the bits you want to preserve or discard.

Example: Bitwise NOT

cpp
#include <iostream>

int main() {
	unsigned char a = 5; // 00000101
	std::cout << (int)(unsigned char)(~a) << std::endl; // 250: every bit flipped
	return 0;
}

Left Shift and Right Shift

<< shifts every bit in a number to the left by the given number of positions, filling the vacated low bits with 0 — and because binary place values double with each position, shifting left by 1 is equivalent to multiplying by 2. >> shifts right the same way, which is equivalent to integer division by 2 for each position shifted.

Example: Left Shift and Right Shift

cpp
#include <iostream>

int main() {
	int x = 4;
	std::cout << (x << 1) << std::endl; // 8: multiply by 2
	std::cout << (x >> 1) << std::endl; // 2: divide by 2
	return 0;
}

Bitwise Compound Assignment

Just like arithmetic operators, bitwise operators have compound assignment forms — &=, |=, ^=, <<=, and >>= — that apply the operation directly to a variable and store the result back into it. These show up constantly in low-level code that manages hardware registers or packed flag fields, where updating a few specific bits without disturbing the rest is a routine operation.

Example: Bitwise Compound Assignment

cpp
#include <iostream>

int main() {
	int flags = 0b0110;
	flags &= 0b0100;
	std::cout << flags << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.