Binary numbers and bitwise operators
🌍 In real life. By the door of a classroom in a Dhaka school there is a switchboard with a row of 4 switches, for 2 lights and 2 fans. When the class leaves, the monitor writes in the caretaker's logbook which ones are still on. Instead of "on, on, off, on", she labels the switches 8, 4, 2 and 1 from the left and writes the sum of the ones that are on: 8 + 4 + 1 = 13. Every pattern of 4 switches gives a different number from 0 to 15, so the caretaker can read the pattern straight back from the number. A computer keeps every whole number exactly this way, as a row of switches.
The idea in one sentence: in binary each place is worth twice the place to its right (1, 2, 4, 8, …), so a number is the sum of the places whose switch is on, and the bitwise operators &, |, ^, << and >> work on those switches directly.
Its words:
- bit: one switch, 0 (off) or 1 (on)
- place value: switch k, counting from 0 on the right, is worth 2 to the power k: 1, 2, 4, 8, …
- bitwise operator: works on the switches place by place:
&(AND) is on where both are on,|(OR) where either is on,^(XOR) where exactly one is on - shift:
x << kslides every switch k places left,x >> kslides them k places right
Step by step: to write n in binary (here 13), keep halving it.
- look at n % 2: that is switch 0, the ones place (13 % 2 = 1: on)
- halve with n // 2, which drops that switch and slides the rest one place right (13 → 6)
- repeat until n is 0: 6 gives 0 (off) and 3; 3 gives 1 (on) and 1; 1 gives 1 (on) and 0
- the switches came out lowest place first (1, 0, 1, 1), so turn them round: 1101
- check by adding the places that are on: 8 + 4 + 1 = 13
Python does both directions for you: bin(13) is '0b1101' and int("1101", 2) is 13. Watch 13 being read off its 4 switches, from the highest place down:
Operators work place by place. Write 12 and 10 one above the other: 1100 and 1010. & keeps the places where both are on: 1000, which is 8. | keeps the places where either is on: 1110, which is 14. ^ keeps the places where exactly one is on: 0110, which is 6. Nothing is carried or borrowed between places, as it is in + and −, so each place is worked out on its own. Watch 12 & 10, one place at a time:
Shifts slide the whole row. x << k moves every switch k places left, and 0s come in on the right. Each on switch doubles in worth for every place it moves, so the number is multiplied by 2 to the power k: 13 << 2 is 13 × 4 = 52. x >> k moves them k places right, and the k lowest switches fall off the end, so it is x // 2 ** k, rounded down: 13 >> 2 is 3. Watch 1101 slide two places left:
One switch at a time. 1 << k is a number with only switch k on, called a mask. With it you can read or change one switch and leave the others alone:
- read switch k:
(n >> k) & 1slides it to the ones place and keeps only that place, so the answer is 0 or 1 - turn it on:
n | (1 << k) - turn it off:
n & ~(1 << k) - flip it:
n ^ (1 << k)
~x (NOT) flips every switch. Python treats a number as if it had endless switches to the left, and a row with every switch on means −1. In x and ~x each place is on in exactly one of the two, so x + ~x is that row, −1, and ~x is always -x - 1: ~13 is −14. So ~(1 << k) has every switch on except switch k, and ANDing with it turns off switch k alone.
Why it works. Every switch except switch 0 is worth an even amount (2, 4, 8, …), so switch 0 is on exactly when n is odd: it is n % 2. Take it away and halve, and what is left is n // 2, whose switches are the rest of n's, one place lower. So the halving loop finds every switch, and since each step has only one possible answer, every whole number has exactly one binary form. Shifts work for the same reason: one place left doubles what each on switch is worth, so it doubles the whole number.
What it costs, by counting. 1,000,000 needs 20 switches: 19 switches reach at most 524,287 (one less than 2 to the power 19), and 20 switches reach 1,048,575. So to_binary(1000000) halves 20 times and keeps 20 digits. A number n has about log₂ n switches, so to_binary is O(log n) time and O(log n) memory. Reading switch 19 by halving would take 19 steps, but (n >> 19) & 1 is 2 operators: O(1) time and O(1) memory for everyday sizes (up to about 2 to the power 63, a few machine steps). Python's whole numbers can grow past that, and then each operator takes time in proportion to the number of switches.
def to_binary(n):
if n == 0:
return "0"
digits = []
while n > 0:
digits.append(str(n % 2)) # switch 0, the ones place: is n odd?
n //= 2 # drop that switch; the rest slide one place right
return "".join(reversed(digits)) # found lowest place first, so turn them round
def bit_at(n, k):
return (n >> k) & 1 # slide switch k to the ones place, keep only that place
def clear_bit(n, k):
return n & ~(1 << k) # ~(1 << k): every switch on except switch k
print(to_binary(13), bin(13), int("1101", 2))
print(12 & 10, 12 | 10, 12 ^ 10)
print(13 << 2, 13 >> 2)
print([bit_at(13, k) for k in range(4)]) # switch 0 first
print(clear_bit(13, 2), 13 | (1 << 1), ~13)Mistakes and edge cases.
^is not a power:2 ^ 3is 1 (the XOR of 10 and 11); a power is2 ** 3, which is 8&is notand:6 and 3is 3 (the last true value), but6 & 3is 2 (the switches both have on)- zero and the
'0b': a halving loop never runs for 0, so return"0"yourself; andbin(5)is'0b101', so slice[2:]for the bits alone ~5is not 2: it flips the endless switches on the left too, so it is −6; to turn switches off, AND with~maskrather than using~on its own- brackets around shifts:
+and-go first, so1 << k + 1means1 << (k + 1); write the brackets you mean
Quiz
What is the binary number 1011 in decimal?
- 11
- 13
- 7
What does this print?
print(6 & 3, 6 | 3, 6 ^ 3)What does this print?
print(2 ^ 3, 2 ** 3)How many times does the loop in to_binary run for n = 1,000,000, and how does that grow with n?
- 20 times: O(log n)
- 1,000,000 times: O(n)
- 7 times, once per decimal digit: O(1)
What does this print?
print(13 >> 1, 7 << 3, ~7)to_binary(6) gives '011' instead of '110'. Which line is wrong?
def to_binary(n): if n == 0: return "0" digits = [] while n > 0: digits.append(str(n % 2)) n //= 2 return "".join(digits)
Coding tasks
Write
to_binary(n): return the binary digits of the whole numbern(0 or more) as a string, without'0b'and without usingbin().to_binary(0)is'0'.Write
bit_at(n, k): return switchkofn(place k, counting from 0 on the right) as the number 0 or 1.Write
clear_bit(n, k): returnnwith switchkturned off and every other switch left as it was. If switch k is already off, returnnunchanged.