Skip to content
BytePatterns

Binary and Bitwise Ops

Bit Manipulation: lesson 1 of 5

Every integer is a row of switches you can address.

Lesson 1 of 5 · 4 min

Binary and Bitwise Ops

Step 1 of 10

To the CPU, 12 is eight switches — the 8 lane and the 4 lane are the only ones on.

The Idea

Bitwise operators work lane by lane, with no carries between lanes. & keeps a 1 only where both sides have one, | where either does, ^ where they differ.

~ flips every lane. Shifts slide the whole row: << doubles, >> halves.

Real-World Example

File permissions are nine bits wide: read, write and execute for owner, group and others. chmod 644 is literally a number, and the kernel answers "may this process write?" with a single AND against a mask — no lookup, no branch.

The Code

a, b = 12, 10           # 0b1100 and 0b1010
print(bin(a), bin(b))   # 0b1100 0b1010
print(a & b)            # 8  -> 1 only where both are 1
print(a | b)            # 14 -> 1 where either is 1
print(a ^ b)            # 6  -> 1 only where they differ
print(~a)               # -13 -> flips every bit, sign included
print(a << 1)           # 24 -> shifting left doubles
print(a >> 2)           # 3  -> shifting right halves, twice

Python

Your turn

What does this print?

x = 5          # 0b101
y = 3          # 0b011
print(x & y, x | y, x ^ y)

Mini quiz

1 / 3

What is `13 & 6`?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.