本书暂未推出简体中文版。现有版本:English。
Primary & Middle School Computer Science · 1–9 年级
25Binary and Hexadecimal
The web page of Noor’s football club writes its orange as #FF8800. A colour, written with letters? The letters are digits: FF8800 is a number, written in base 16. This chapter explains how numbers are written in base 2, the base of the machine, and in base 16, the short way people write base 2.
You already know
A bit is a 0 or a 1, a byte is eight bits, and each extra bit doubles the number of patterns (Chapter 11). A colour on a screen is made of three numbers from 0 to 255, for red, green and blue (Chapter 12). In mathematics, the place of a digit gives its value (in 352, the 3 is worth 300), and means .
25.1 Place value in base 2
Definition 25.1 (Number base)
A number base is the number of digits a way of writing numbers uses. In base , each place is worth times the place on its right: the places are worth 1, , , , and so on, from the right.
Our usual numbers are in base 10: the places are worth 1, 10, 100, 1 000. Binary is base 2: the places are worth 1, 2, 4, 8, 16, 32…, the powers of 2, exactly the dots on the cards of Chapter 11. A binary number is the sum of the places where it has a 1.
To read a binary number with a program, walk through its bits from the left. Each new bit shifts everything one place to the left, which doubles the value so far, then adds itself.
bits = "101100"
value = 0
for bit in bits:
value = value * 2 + int(bit) # shift one place left, then add the new bit
print(bit, "->", value)
print(bits, "in binary is", value)
$ python to_decimal.py
1 -> 1
0 -> 2
1 -> 5
1 -> 11
0 -> 22
0 -> 44
101100 in binary is 44
25.2 Converting both ways
The other way, from decimal to binary, divides by 2 again and again. The remainder of each division, 0 or 1, is the next bit from the right, and the quotient is what remains to be written.
Method 25.2 (Decimal to binary)
Divide the number by 2, and write down the remainder. Divide the quotient by 2 again, and go on until the quotient is 0. The remainders, read from the last to the first, are the bits of the number.
n = 44
remainders = []
while n > 0:
print(n, "= 2 x", n // 2, "+", n % 2)
remainders.append(n % 2)
n = n // 2
bits = ""
for r in remainders:
bits = str(r) + bits # the last remainder ends up first
print("binary:", bits)
$ python to_binary.py
44 = 2 x 22 + 0
22 = 2 x 11 + 0
11 = 2 x 5 + 1
5 = 2 x 2 + 1
2 = 2 x 1 + 0
1 = 2 x 0 + 1
binary: 101100
Python can check both programs. bin writes a number in binary, with 0b in front to show the base; int(text, 2) reads a text as a binary number. A number can also be typed directly in binary, 0b101100.
print(bin(44), int("101100", 2))
print(hex(255), int("ff", 16), int("FF", 16))
print(bin(255), hex(44), 0x2C, 0b101100)
$ python base_functions.py
0b101100 44
0xff 255 255
0b11111111 0x2c 44 44
hex and base 16 come in a few pages.25.3 Adding in binary
Binary numbers are added like decimal ones, column by column from the right, but a column overflows as soon as it reaches 2: is 10 in binary, so the column gets a 0 and a 1 goes into the next one.
Definition 25.3 (Carry)
In a column addition, the carry is the digit passed to the next column on the left when a column’s sum does not fit in one digit. In binary, a column of writes 0 with a carry of 1, and writes 1 with a carry of 1.
The program does the same with two strings of bits. It walks the columns from the right with range(len(a) - 1, -1, -1), which counts down to 0, and keeps the carry in a variable:
def add_binary(a, b):
"""Add two strings of bits of the same length, column by column from the right."""
result = ""
carry = 0
for i in range(len(a) - 1, -1, -1):
total = int(a[i]) + int(b[i]) + carry
result = str(total % 2) + result
carry = total // 2
if carry == 1:
result = "1" + result
return result
print(add_binary("01101101", "00111011"))
print(add_binary("11001000", "01110000"))
$ python add_binary.py
10101000
100111000
The second sum has a carry out of the leftmost column: the answer has nine bits and no longer fits in a byte. A machine that keeps only eight bits has to do something about it; the next book explains what.
25.4 Hexadecimal
Long rows of 0s and 1s are hard to read and easy to mistype. People therefore write them in base 16.
Definition 25.4 (Hexadecimal)
Hexadecimal is base 16. Its sixteen hexadecimal digits are 0 to 9, then A, B, C, D, E and F for ten to fifteen.
Since , one hexadecimal digit stands for exactly four bits. To turn binary into hexadecimal, cut the bits into groups of four from the right, and write each group as one digit:
DIGITS = "0123456789ABCDEF"
def to_hex(bits):
"""Hexadecimal digits of a string of bits whose length is a multiple of 4."""
result = ""
for i in range(0, len(bits), 4):
group = bits[i:i + 4]
result = result + DIGITS[int(group, 2)]
return result
for bits in ["10101000", "11111111", "0010110000001111"]:
print(bits, "->", to_hex(bits))
$ python to_hex.py
10101000 -> A8
11111111 -> FF
0010110000001111 -> 2C0F
In Python, hex writes a number in hexadecimal with 0x in front, int(text, 16) reads one, and 0x2C can be typed directly (Output 25.3). Python writes the letters in small type, 0xff; both are correct.
25.5 Colours, and what bits can hold
A colour in a web page is written #RRGGBB: a #, then three pairs of hexadecimal digits, for red, green and blue. Each pair is one byte, from 00 to FF, that is from 0 to 255.
def rgb(code):
"""The three numbers of a colour written #RRGGBB."""
red = int(code[1:3], 16)
green = int(code[3:5], 16)
blue = int(code[5:7], 16)
return [red, green, blue]
for code in ["#FF8800", "#2E8B57", "#4169E1"]:
print(code, rgb(code))
$ python colours.py
#FF8800 [255, 136, 0]
#2E8B57 [46, 139, 87]
#4169E1 [65, 105, 225]
Why do the three numbers stop at 255? Because a byte has 8 bits, and 8 bits make 256 patterns. The doubling of Chapter 11 gives the general rule:
Proposition 25.5 (Patterns of bits)
With bits there are different patterns. Read as binary numbers, they are the whole numbers from 0 to .
Proof. One bit has 2 patterns, 0 and 1. Adding a bit on the left turns each pattern into two, one with a 0 in front and one with a 1, so the number of patterns doubles: , , , and after bits, . The smallest is all zeros, the number 0. The largest is all ones, ; adding 1 to it carries through every column and gives a 1 followed by zeros, which is . So the largest is . ∎
patterns = []
for a in "01":
for b in "01":
for c in "01":
patterns.append(a + b + c)
print(len(patterns), "patterns of 3 bits:", patterns)
count = 1 # 0 bits: one pattern, the empty one
for n in range(1, 11):
count = count * 2 # one more bit: each pattern gets a 0 or a 1
print("n =", n, ":", count, "patterns, largest number", count - 1)
$ python count_patterns.py
8 patterns of 3 bits: ['000', '001', '010', '011', '100', '101', '110', '111']
n = 1 : 2 patterns, largest number 1
n = 2 : 4 patterns, largest number 3
n = 3 : 8 patterns, largest number 7
n = 4 : 16 patterns, largest number 15
n = 5 : 32 patterns, largest number 31
n = 6 : 64 patterns, largest number 63
n = 7 : 128 patterns, largest number 127
n = 8 : 256 patterns, largest number 255
n = 9 : 512 patterns, largest number 511
n = 10 : 1024 patterns, largest number 1023
25.6 Exercises
Exercise 25.1 ★
What do bin(10) and int("1101", 2) give?
Solution
Solution of Exercise 25.1.
bin(10) is "0b1010" (), and int("1101", 2) is .
Exercise 25.2 ★
What does hex(255) give? And int("1F", 16)?
Solution
Solution of Exercise 25.2.
hex(255) is "0xff": . int("1F", 16) is .
Exercise 25.3 ★
In Listing 25.2, n is changed to 13. What does the program print?
Solution
Solution of Exercise 25.3.
The divisions , , and , each on its line, then binary: 1101.
Exercise 25.4 ★
Write a function to_binary(n) that returns the binary writing of a whole number by repeated division, without bin. What must it return for 0?
Solution
Solution of Exercise 25.4.
def to_binary(n):
"""The binary writing of a whole number n >= 0, by repeated division by 2."""
if n == 0:
return "0"
bits = ""
while n > 0:
bits = str(n % 2) + bits
n = n // 2
return bits
print(to_binary(13), to_binary(0), to_binary(255))
For 0 the loop never runs, so the function must return "0" itself; an empty string would not be a number. It prints 1101 0 11111111, and a test of the chapter compares it with bin for 0 to 599.
Exercise 25.5 ★★
This program should print 110, the binary writing of 6. What does it print, and why? Fix it.
n = 6
bits = ""
while n > 0:
bits = bits + str(n % 2)
n = n // 2
print(bits)
Exercise 25.6 ★★
int("102", 2) stops the program with an error. Why? Write a function is_binary(text) that a program can call before converting.
Solution
Solution of Exercise 25.6.
2 is not a binary digit, so "102" is not a binary number, and Python reports a ValueError.
def is_binary(text):
"""True when text is not empty and every character is 0 or 1."""
if len(text) == 0:
return False
for ch in text:
if ch != "0" and ch != "1":
return False
return True
for text in ["1101", "102", ""]:
if is_binary(text):
print(text, "->", int(text, 2))
else:
print(text, "is not a binary number")
The empty text is refused too: it has no digit at all.
Exercise 25.7 ★★
Change add_binary so that it adds two strings of bits of different lengths, such as "1011" and "110".
Solution
Solution of Exercise 25.7.
Put zeros in front of the shorter string until both have the same length, then add as before:
def add_binary(a, b):
"""Add two strings of bits of any lengths."""
while len(a) < len(b):
a = "0" + a
while len(b) < len(a):
b = "0" + b
result = ""
carry = 0
for i in range(len(a) - 1, -1, -1):
total = int(a[i]) + int(b[i]) + carry
result = str(total % 2) + result
carry = total // 2
if carry == 1:
result = "1" + result
return result
print(add_binary("1011", "110"), add_binary("1", "1111"))
From line 7 on it is Listing 25.4; it prints 10001 () and 10000 ().
Exercise 25.8 ★★
Write a function colour_code(red, green, blue) that returns the #RRGGBB code of three numbers from 0 to 255, with two capital hexadecimal digits for each.
Solution
Solution of Exercise 25.8.
The first digit is the quotient by 16, the second the remainder:
DIGITS = "0123456789ABCDEF"
def two_hex(n):
"""A number from 0 to 255 as two hexadecimal digits."""
return DIGITS[n // 16] + DIGITS[n % 16]
def colour_code(red, green, blue):
return "#" + two_hex(red) + two_hex(green) + two_hex(blue)
print(colour_code(255, 136, 0), colour_code(46, 139, 87), colour_code(0, 0, 0))
It prints #FF8800 #2E8B57 #000000, the codes of Output 25.6 and black.
Exercise 25.9 ★★
How many different patterns do 12 bits have? What is the largest number they can write?
Solution
Solution of Exercise 25.9.
patterns; the largest number is .
Exercise 25.10 ★★★
What is the largest number on 16 bits, in decimal and in hexadecimal?
Solution
Solution of Exercise 25.10.
, written FFFF: sixteen ones make four groups of 1111, four Fs.
Exercise 25.11 ★★★
Prove that every whole number from 0 to has exactly one writing with bits (zeros in front allowed). Hint: every number has at least one (by repeated division); then count the patterns and the numbers.
Solution
Solution of Exercise 25.11.
Every number from 0 to has a writing with bits: repeated division gives its bits, at most of them since the number is below , and zeros in front fill the places. So each of the numbers gets at least one of the patterns. There are exactly patterns, and each pattern is the writing of only one number. If one number had two patterns, the numbers would use more than patterns, which do not exist. So each number has exactly one.
Exercise 25.12 ★★★
Write a function convert(text, from_base, to_base) that converts a number between any two bases from 2 to 16, through a whole number in the middle.
Solution
Solution of Exercise 25.12.
Read the text into a whole number (the doubling walk of Listing 25.1, with the base instead of 2), then write that number in the other base (repeated division):
DIGITS = "0123456789ABCDEF"
def to_number(text, base):
value = 0
for ch in text.upper():
value = value * base + DIGITS.find(ch)
return value
def from_number(n, base):
if n == 0:
return "0"
text = ""
while n > 0:
text = DIGITS[n % base] + text
n = n // base
return text
def convert(text, from_base, to_base):
return from_number(to_number(text, from_base), to_base)
print(convert("101100", 2, 16), convert("FF", 16, 2))
print(convert("255", 10, 8), convert("777", 8, 3))
It prints 2C 11111111 and 377 200221. A test converts many numbers to every base from 2 to 16 and back.
25.7 Problem: The Grains of Rice
Problem 25.1
Weekend problem — the chessboard and the grains of rice
An old story tells of a king who offered a reward to the inventor of chess. The inventor asked for rice: one grain on the first square of the board, two on the second, four on the third, and so on, doubling at each of the 64 squares. The king laughed at so small a reward.
Part I — The first row.
- How many grains are on squares 1 to 8? Write each as a power of 2.
- What is the total on the first 8 squares? Compare it with the number of grains on square 9.
- Write the number of grains on square , and the total on the first 8 squares, in binary. Why is the total all ones?
Part II — The whole board.
grains = 1
total = 0
for square in range(1, 65):
total = total + grains
if square <= 8 or square == 64:
print("square", square, ":", grains, "grains, total", total)
grains = grains * 2
print("total:", total)
print("2 ** 64 - 1 =", 2 ** 64 - 1)
print("binary:", bin(total)[2:].count("1"), "ones,", len(bin(total)) - 2, "bits")
print("hexadecimal:", hex(total)[2:].upper())
- Why does the variable
grainsdouble after it is added, and not before? - Run the program. How many grains are on the last square, and how many in total?
- Check that the total is , and explain why with the proposition of this chapter.
- How many ones does the total have in binary? How many hexadecimal digits, and which?
- Suppose that a grain of rice weighs 25 milligrams. Roughly how many tonnes is the total? (A tonne is a thousand million milligrams.)
Part III — Counting with a machine.
- How many bytes does the total need?
- A counter of 32 bits counts the grains one by one. Up to which square can it count the total without running out of patterns?
- How many bits does a computer need to count every grain of the board, from 0 to the total?
- State the result.
Solution
Solution of Problem 25.1.
1. 1, 2, 4, 8, 16, 32, 64, 128: square holds grains.
2. , one less than the 256 grains of square 9.
3. Square holds a 1 followed by zeros; the total on 8 squares is 11111111: each square adds a different power of 2, so each place has exactly one 1.
4. The first square must count 1 grain; doubling first would start the board at 2.
5. The program prints:
$ python grains.py
square 1 : 1 grains, total 1
square 2 : 2 grains, total 3
square 3 : 4 grains, total 7
square 4 : 8 grains, total 15
square 5 : 16 grains, total 31
square 6 : 32 grains, total 63
square 7 : 64 grains, total 127
square 8 : 128 grains, total 255
square 64 : 9223372036854775808 grains, total 18446744073709551615
total: 18446744073709551615
2 ** 64 - 1 = 18446744073709551615
binary: 64 ones, 64 bits
hexadecimal: FFFFFFFFFFFFFFFF
The last square holds grains, more than nine billion billion, and the total is almost twice as much.
6. The total is : in binary, 64 ones. By the proposition, the largest number on 64 bits is ; the program’s two lines agree.
7. 64 ones, so 16 groups of 1111: sixteen Fs.
8. About grains of 25 milligrams make about milligrams, that is about tonnes: some 460 billion tonnes of rice.
10. 32 bits count up to , which is exactly the total on the first 32 squares; the 33rd square goes past it.
11. 64 bits: the total is the largest number they can write.
12. Result. The board holds 18 446 744 073 709 551 615 grains, , written as sixteen Fs in hexadecimal: exactly the largest number that 8 bytes can hold.