🇯🇵 日本語 | 🇺🇸 English
Advertisement

Bitwise Operators

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 ( & )
ABA&B
000
010
100
111
1 only when both are 1
OR ( | )
ABA|B
000
011
101
111
1 if either is 1
XOR ( ^ )
ABA^B
000
011
101
110
1 only when they differ
NOT ( ~ )
A~A
01
10
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)
// 5 in binary
//   00000101 = 5
// 5 << 2
//   00010100 = 20  (5 x 4)
// 20 >> 1
//   00001010 = 10  (20 / 2)
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");
else        printf("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 = 4

int perm = 0;
perm |= FLAG_READ;              // turn flag ON
perm |= FLAG_WRITE;             // turn flag ON
if (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 color
int r = (color >> 16) & 0xFF;  // 255
int g = (color >> 8)  & 0xFF;  // 87
int 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.
Share this article
Share on X Share on Facebook