Skip to content
Codescope

Bitwise operations

Eight switches in a byte. These operators flip them in parallel.

core10 min9 steps

Before you start

Every byte is really 8 bits — 8 tiny on/off switches. Normally you don't care; you work with the whole byte as a number. But sometimes you *do* care about individual bits: file permissions, feature flags, graphics colours.

**Bitwise operators** let you work with those individual switches. & (AND), | (OR), ^ (XOR), ~ (NOT), and the shift operators << >> — five operators, each doing one thing per bit, all at the same time.

This lesson visualises those 8 switches and shows what each operator does to them, so you can read flags & 0x04 and know exactly which switch you are checking.

One byte

8 bits · value = sum of the set powers of two
bit
7
6
5
4
3
2
1
0
a
0
0
1
0
1
1
0
0
44 · 0010 1100
b
0
0
0
1
1
0
1
0
26 · 0001 1010

Bit n is worth 2ⁿ. Bit 5 is 32, bit 3 is 8, bit 2 is 4 — that is the whole encoding.

Step 1 of 9. A byte is eight independent bits. `a = 44` is not really "forty-four" in memory. It is the pattern `0010 1100` — bits 5, 3 and 2 switched on, and 32 + 8 + 4 = 44. Bitwise operators ignore the number entirely and work on the switches, one column at a time, all eight in a single instruction.

01 / 09

Step 01 / 09

A byte is eight independent bits

a = 44 is not really "forty-four" in memory. It is the pattern 0010 1100 — bits 5, 3 and 2 switched on, and 32 + 8 + 4 = 44.

Bitwise operators ignore the number entirely and work on the switches, one column at a time, all eight in a single instruction.

bitwise-operations.cC
#include <stdio.h>#define READ (1u << 2)      /* 0000 0100 */int main(void) {    unsigned char a = 44;   /* 0010 1100 */    unsigned char b = 26;   /* 0001 1010 */    printf("%d\n", a & b);              /* 8   */    printf("%d\n", a | b);              /* 62  */    printf("%d\n", a ^ b);              /* 54  */    printf("%d\n", (unsigned char)~a);  /* 211 */    printf("%d\n", a << 1);             /* 88  */    printf("%d\n", a >> 2);             /* 11  */    unsigned char perms = 0;    perms |= READ;                      /* set   */    if (perms & READ) puts("readable"); /* test  */    perms &= ~READ;                     /* clear */    return 0;}