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

C Bitwise Operators

Bitwise AND (&)

& compares two numbers bit by bit and produces a 1 in each position where both operands have a 1, and a 0 everywhere else -- often used to check or isolate specific bits within a value, like reading configuration flags.

Example: Bitwise AND (&)

c
#include <stdio.h>
int main() {
	int a = 6, b = 3;
	printf("%d", a & b);
	return 0;
}

Bitwise OR (|)

| compares two numbers bit by bit and produces a 1 in each position where at least one operand has a 1 -- commonly used to turn on specific bits without disturbing the others, such as setting a flag inside a bitmask.

Example: Bitwise OR (|)

c
#include <stdio.h>
int main() {
	int a = 6, b = 3;
	printf("%d", a | b);
	return 0;
}

Bitwise XOR (^)

^ (XOR) produces a 1 in each bit position where the two operands differ, and a 0 where they match -- a classic use is toggling a bit on or off, or swapping two values without a temporary variable.

Example: Bitwise XOR (^)

c
#include <stdio.h>
int main() {
	int a = 6, b = 3;
	printf("%d", a ^ b);
	return 0;
}

Bitwise NOT ()

~ is a unary operator that flips every bit of its single operand -- every 1 becomes 0 and every 0 becomes 1 -- which for a signed integer effectively produces its bitwise complement, not simply its negative.

Example: Bitwise NOT ()

c
#include <stdio.h>
int main() {
	int a = 5;
	printf("%d", ~a);
	return 0;
}

Shift Operators (<< and >>)

<< shifts all bits left by a given number of positions (equivalent to multiplying by a power of 2), while >> shifts them right (roughly equivalent to integer division by a power of 2) -- both are much faster than actual multiplication or division.

Example: Shift Operators (<< and >>)

c
#include <stdio.h>
int main() {
	int a = 4;
	printf("%d %d", a << 1, a >> 1);
	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.