Learn the bitwise operators that let you manipulate data at the binary level.
What are bitwise operators?
Internally, computers represent all data as binary (bit sequences). Bitwise operators let you directly manipulate each bit of that binary representation.
Logical
& | ^ ~
Shift
<< >>
What are they used for? Flag management, masking, fast multiplication/division, hardware control, cryptography, and more. They are essential in embedded and systems programming.
Prerequisite: Decimal 12 is 00001100 in binary. Each digit (0 or 1) represents a bit of the value.
AND, OR, XOR, NOT
These operators perform a logical operation on each bit.
AND ( & )
A
B
A&B
0
0
0
0
1
0
1
0
0
1
1
1
1 only when both are 1
OR ( | )
A
B
A|B
0
0
0
0
1
1
1
0
1
1
1
1
1 if either is 1
XOR ( ^ )
A
B
A^B
0
0
0
0
1
1
1
0
1
1
1
0
1 only when they differ
NOT ( ~ )
A
~A
0
1
1
0
Bit inversion
Example
0b11001010 (= 202)
& 0b10101010 (= 170)
-----------
0b10001010 (= 138) // Only bits that are 1 in both remain
Shift Operations (<<, >>)
These operators shift a bit sequence 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/division, so they are used where performance matters.
Use Cases
Odd/even check
if (n & 1) printf("odd\n");
elseprintf("even\n");
// Odd if the lowest bit is 1, even if 0
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 flag ON
perm |= FLAG_WRITE; // turn flag ONif (perm & FLAG_READ) ... // check flag
perm &= ~FLAG_WRITE; // turn flag OFF
Linux file permissions (rwx = read/write/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 and see the result of each bitwise operation.
Press "Calculate".
Quiz
What is the result of 0b1100 & 0b1010?
0b1000 (8)
0b1110 (14)
0b0110 (6)
0b1010 (10)
Explanation: AND yields 1 only where both bits are 1. 1100 & 1010 → 1000 (= 8). Only the 3rd bit from the right is 1 in both.
By what factor does n << 3 multiply n?
x3
x6
x8
x16
Explanation: Shifting left n times multiplies by 2n. n << 3 = n × 23 = n × 8.