Bitwise operators let you manipulate data directly at the bit level.
📖 What you'll learn on this page
✅ Must-know essentials
& (AND), | (OR), ^ (XOR), ~ (NOT)
<< (left shift) multiplies by 2, >> (right shift) divides by 2
⭐ Read if you have time
Managing on/off flags
Using bit masks to extract specific bits
Signed right shift is implementation-defined
What are bitwise operators?
Computers represent all data internally as binary (sequences of bits). Bitwise operators let you manipulate each bit of that representation directly.
Logical
& | ^ ~
Shift
<< >>
What are they used for? Flag management, masking, fast multiplication and division, hardware control, cryptography, and more. They're essential in embedded and systems programming.
Prerequisite: Decimal 12 is 00001100 in binary. Each digit (0 or 1) is one bit of the value.
AND, OR, XOR, NOT
These operators apply a logical operation to each bit independently.
AND ( & )
A
B
A&B
0
0
0
0
1
0
1
0
0
1
1
1
1 only when both bits are 1
OR ( | )
A
B
A|B
0
0
0
0
1
1
1
0
1
1
1
1
1 if either bit is 1
XOR ( ^ )
A
B
A^B
0
0
0
0
1
1
1
0
1
1
1
0
1 only when the bits differ
NOT ( ~ )
A
~A
0
1
1
0
Flips every bit
Example
0b11001010 (= 202)
& 0b10101010 (= 170)
-----------
0b10001010 (= 138) // Only bits set in both operands remain
Shift Operations (<<, >>)
These operators shift a sequence of bits to the left or right.
Left shift ( << )
a << n = a × 2n 5 << 1 → 10 (5×2) 5 << 3 → 40 (5×8)
Right shift ( >> )
a >> n = a ÷ 2n (truncating) 40 >> 1 → 20 (40÷2) 40 >> 3 → 5 (40÷8)
Shift left by 1 = multiply by 2. Shift right by 1 = divide by 2. Shifts are faster than multiplication and division, so they're common in performance-sensitive code.
Use Cases
Odd/even check
if (n & 1) printf("odd\n");
elseprintf("even\n");
// The lowest bit is 1 for odd numbers and 0 for even numbers
Flag management
#define FLAG_READ (1 << 0) // 0001 = 1#define FLAG_WRITE (1 << 1) // 0010 = 2#define FLAG_EXEC (1 << 2) // 0100 = 4int perm = 0;
perm |= FLAG_READ; // turn the flag ON
perm |= FLAG_WRITE; // turn the flag ONif (perm & FLAG_READ) ... // check whether the flag is set
perm &= ~FLAG_WRITE; // turn the flag OFF
Linux file permissions (rwx for read, write, and execute) are exactly this kind of bit-flag scheme.
Extracting specific bits (masking)
int color = 0xFF5733; // RGB colorint r = (color >> 16) & 0xFF; // 255int g = (color >> 8) & 0xFF; // 87int b = color & 0xFF; // 51
Bitwise Calculator
Enter two numbers to see the result of each bitwise operation.
Press Calculate to see the results.
Review Quiz
What is the result of 0b1100 & 0b1010?
0b1000 (8)
0b1110 (14)
0b0110 (6)
0b1010 (10)
Explanation: AND produces 1 only where both bits are 1. 1100 & 1010 → 1000 (= 8). Only the 3rd bit from the right is set in both operands.
By what factor does n << 3 multiply n?
x3
x6
x8
x16
Explanation: Shifting left by n positions multiplies by 2n. n << 3 = n × 23 = n × 8.