---
title: "Binary and Hexadecimal"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 25
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 25 — Binary and Hexadecimal

The [web page](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-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](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) is a 0 or a 1, a [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) is eight [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), and each extra [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) doubles the number of patterns ([Chapter 11](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#ch-g5-bits-and-bytes)). A colour on a screen is made of three numbers from 0 to 255, for red, green and blue ([Chapter 12](https://one-course.com/books/computer-science/1/en/chapter/12-text-pictures-and-sound-as-numbers#ch-g5-text-pictures-sound-as-numbers)). In mathematics, the place of a digit gives its [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) (in 352, the 3 is worth 300), and $2^5$ means $2 \times 2 \times 2 \times 2 \times 2$.

## 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 $b$, each place is worth $b$ times the place on its right: the places are worth 1, $b$, $b^2$, $b^3$, and so on, from the right.

Our usual numbers are in base 10: the places are worth 1, 10, 100, 1 000. [Binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-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](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#ch-g5-bits-and-bytes). A [binary number](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) is the sum of the places where it has a 1.

![The same idea in two bases: the value of each place, and the digits of 352 in base 10 and of 44 in base 2.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-binary-and-hexadecimal/fig-9a627015243d.svg)

*The same idea in two bases: the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of each place, and the digits of 352 in base 10 and of 44 in base 2.*

To read a [binary number](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) with a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program), walk through its [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) from the left. Each new [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) shifts everything one place to the left, which doubles the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) so far, then adds itself.

```python
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)
```

***Listing 25.1.** From [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) to decimal. code/grade-8/01-binary-and-hexadecimal/listings/to_decimal.py*

```
$ python to_decimal.py
1 -> 1
0 -> 2
1 -> 5
1 -> 11
0 -> 22
0 -> 44
101100 in binary is 44
```

***Output 25.1.** The [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) after each [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit).*

## 25.2 Converting both ways

The other way, from decimal to [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), divides by 2 again and again. The remainder of each division, 0 or 1, is the next [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-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](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) of the number.

![The division ladder for 44: the last remainder is the first bit.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-binary-and-hexadecimal/fig-ed0778c7ad50.svg)

*The division ladder for 44: the last remainder is the first [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit).*

```python
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)
```

***Listing 25.2.** From decimal to [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary). code/grade-8/01-binary-and-hexadecimal/listings/to_binary.py*

```
$ 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
```

***Output 25.2.** Each division, then the [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit).*

Python can check both [programs](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program). `bin` writes a number in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), with `0b` in front to show the base; `int(text, 2)` reads a text as a [binary number](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary). A number can also be typed directly in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), `0b101100`.

```python
print(bin(44), int("101100", 2))
print(hex(255), int("ff", 16), int("FF", 16))
print(bin(255), hex(44), 0x2C, 0b101100)
```

***Listing 25.3.** Python’s own conversions. code/grade-8/01-binary-and-hexadecimal/listings/base_functions.py*

```
$ python base_functions.py
0b101100 44
0xff 255 255
0b11111111 0x2c 44 44
```

***Output 25.3.** The same 44, four times; `hex` and base 16 come in a few pages.*

## 25.3 Adding in binary

[Binary numbers](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) are added like decimal ones, column by column from the right, but a column overflows as soon as it reaches 2: $1 + 1$ is 10 in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-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](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), a column of $1 + 1$ writes 0 with a carry of 1, and $1 + 1 + 1$ writes 1 with a carry of 1.

![Adding two bytes: the carries, in red, ride above the columns.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-binary-and-hexadecimal/fig-21315e51de49.svg)

*Adding two [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte): the carries, in red, ride above the columns.*

The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) does the same with two [strings](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) of [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). It walks the columns from the right with `range(len(a) - 1, -1, -1)`, which counts down to 0, and keeps the [carry](#def-g8-binary-and-hexadecimal-carry) in a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value):

```python
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"))
```

***Listing 25.4.** Column addition of two [strings](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) of [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). code/grade-8/01-binary-and-hexadecimal/listings/add_binary.py*

```
$ python add_binary.py
10101000
100111000
```

***Output 25.4.** $109 +
59 = 168$, then $200 + 112 = 312$, which needs nine [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit).*

The second sum has a [carry](#def-g8-binary-and-hexadecimal-carry) out of the leftmost column: the answer has nine [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) and no longer fits in a [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte). A machine that keeps only eight [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) 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 $16 = 2^4$, one [hexadecimal digit](#def-g8-binary-and-hexadecimal-hexadecimal) stands for exactly four [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). To turn [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) into [hexadecimal](#def-g8-binary-and-hexadecimal-hexadecimal), cut the [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) into groups of four from the right, and write each group as one digit:

![A byte is two hexadecimal digits: one for each group of four bits.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-binary-and-hexadecimal/fig-d625a6d53629.svg)

*A [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) is two [hexadecimal digits](#def-g8-binary-and-hexadecimal-hexadecimal): one for each group of four [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit).*

```python
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))
```

***Listing 25.5.** [Binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) to [hexadecimal](#def-g8-binary-and-hexadecimal-hexadecimal), four [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) at a time. code/grade-8/01-binary-and-hexadecimal/listings/to_hex.py*

```
$ python to_hex.py
10101000 -> A8
11111111 -> FF
0010110000001111 -> 2C0F
```

***Output 25.5.** Sixteen [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) are only four [hexadecimal digits](#def-g8-binary-and-hexadecimal-hexadecimal).*

In Python, `hex` writes a number in [hexadecimal](#def-g8-binary-and-hexadecimal-hexadecimal) with `0x` in front, `int(text, 16)` reads one, and `0x2C` can be typed directly ([Output 25.3](#out-g8-binary-and-hexadecimal-base-functions)). Python writes the letters in small type, `0xff`; both are correct.

## 25.5 Colours, and what $n$ bits can hold

A colour in a [web page](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-page) is written `#RRGGBB`: a `#`, then three pairs of [hexadecimal digits](#def-g8-binary-and-hexadecimal-hexadecimal), for red, green and blue. Each pair is one [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), from `00` to `FF`, that is from 0 to 255.

```python
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))
```

***Listing 25.6.** Three colours split into their three numbers. code/grade-8/01-binary-and-hexadecimal/listings/colours.py*

```
$ python colours.py
#FF8800 [255, 136, 0]
#2E8B57 [46, 139, 87]
#4169E1 [65, 105, 225]
```

***Output 25.6.** Red, green and blue of each colour.*

![The three colours of , drawn from the same codes.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-binary-and-hexadecimal/fig-7f5211c81516.svg)

*The three colours of [Listing 25.6](#lst-g8-binary-and-hexadecimal-colours), drawn from the same codes.*

Why do the three numbers stop at 255? Because a [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) has 8 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), and 8 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) make 256 patterns. The doubling of [Chapter 11](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#ch-g5-bits-and-bytes) gives the general rule:

**Proposition 25.5 (Patterns of nnn bits).**

With $n$ [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) there are $2^n$ different patterns. Read as [binary numbers](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), they are the whole numbers from 0 to $2^n - 1$.

**Proof.** One [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) has 2 patterns, 0 and 1. Adding a [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-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: $2$, $2 \times 2 = 2^2$, $2^3$, and after $n$ [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), $2^n$. The smallest is all zeros, the number 0. The largest is all ones, $1 + 2 + 4 + \dots + 2^{n-1}$; adding 1 to it carries through every column and gives a 1 followed by $n$ zeros, which is $2^n$. So the largest is $2^n - 1$. ∎

```python
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)
```

***Listing 25.7.** All patterns of three [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), then the counts up to ten [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). code/grade-8/01-binary-and-hexadecimal/listings/count_patterns.py*

```
$ 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
```

***Output 25.7.** Each extra [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) doubles the count.*

## 25.6 Exercises

**Exercise 25.1 ★.**

What do `bin(10)` and `int("1101", 2)` give?

**Solution of Exercise 25.1.**

`bin(10)` is `"0b1010"` ($8 + 2$), and `int("1101", 2)` is $8 + 4 + 1 = 13$.

**Exercise 25.2 ★.**

What does `hex(255)` give? And `int("1F", 16)`?

**Solution of Exercise 25.2.**

`hex(255)` is `"0xff"`: $255 = 15 \times 16 + 15$. `int("1F", 16)` is $1 \times 16 + 15 = 31$.

**Exercise 25.3 ★.**

In [Listing 25.2](#lst-g8-binary-and-hexadecimal-to-binary), `n` is changed to 13. What does the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) print?

**Solution of Exercise 25.3.**

The divisions $13 = 2 \times 6 + 1$, $6 = 2 \times 3 + 0$, $3 = 2 \times 1 + 1$ and $1 = 2 \times 0 + 1$, each on its line, then `binary: 1101`.

**Exercise 25.4 ★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `to_binary(n)` that returns the [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) writing of a whole number by repeated division, without `bin`. What must it return for 0?

**Solution of Exercise 25.4.**

```python
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))
```

*Decimal to [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), as a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function). code/grade-8/01-binary-and-hexadecimal/exercises/to_binary_fn.py*

For 0 the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) never runs, so the [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) must return `"0"` itself; an empty [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) should print 110, the [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) writing of 6. What does it print, and why? Fix it.

```python
n = 6
bits = ""
while n > 0:
    bits = bits + str(n % 2)
    n = n // 2
print(bits)
```

***Listing 25.8.** Remainders in the wrong order. code/grade-8/01-binary-and-hexadecimal/exercises/downwards_bug.py*

**Solution of Exercise 25.5.**

It prints `011`: each remainder is added at the end, so the first one, the [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) on the right, comes out first. Adding each [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) in front, `bits = str(n % 2) + bits`, gives `110`.

**Exercise 25.6 ★★.**

`int("102", 2)` stops the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) with an error. Why? Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `is_binary(text)` that a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) can call before converting.

**Solution of Exercise 25.6.**

2 is not a [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) digit, so `"102"` is not a [binary number](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), and Python reports a `ValueError`.

```python
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")
```

*A check before converting. code/grade-8/01-binary-and-hexadecimal/exercises/is_binary.py*

The empty text is refused too: it has no digit at all.

**Exercise 25.7 ★★.**

Change `add_binary` so that it adds two [strings](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) of [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) of different lengths, such as `"1011"` and `"110"`.

**Solution of Exercise 25.7.**

Put zeros in front of the shorter [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) until both have the same length, then add as before:

```python
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"))
```

*Making the lengths equal. code/grade-8/01-binary-and-hexadecimal/exercises/add_any.py*

From line 7 on it is [Listing 25.4](#lst-g8-binary-and-hexadecimal-add); it prints `10001` ($11 + 6 = 17$) and `10000` ($1 + 15 = 16$).

**Exercise 25.8 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `colour_code(red, green, blue)` that returns the `#RRGGBB` code of three numbers from 0 to 255, with two capital [hexadecimal digits](#def-g8-binary-and-hexadecimal-hexadecimal) for each.

**Solution of Exercise 25.8.**

The first digit is the quotient by 16, the second the remainder:

```python
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))
```

*Three numbers to a colour code. code/grade-8/01-binary-and-hexadecimal/exercises/to_code.py*

It prints `#FF8800 #2E8B57 #000000`, the codes of [Output 25.6](#out-g8-binary-and-hexadecimal-colours) and black.

**Exercise 25.9 ★★.**

How many different patterns do 12 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) have? What is the largest number they can write?

**Solution of Exercise 25.9.**

$2^{12} = 4\,096$ patterns; the largest number is $4\,095$.

**Exercise 25.10 ★★★.**

What is the largest number on 16 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), in decimal and in [hexadecimal](#def-g8-binary-and-hexadecimal-hexadecimal)?

**Solution of Exercise 25.10.**

$2^{16} - 1 = 65\,535$, written `FFFF`: sixteen ones make four groups of `1111`, four `F`s.

**Exercise 25.11 ★★★.**

Prove that every whole number from 0 to $2^n - 1$ has exactly one writing with $n$ [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) (zeros in front allowed). Hint: every number has at least one (by repeated division); then count the patterns and the numbers.

**Solution of Exercise 25.11.**

Every number from 0 to $2^n - 1$ has a writing with $n$ [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit): repeated division gives its [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), at most $n$ of them since the number is below $2^n$, and zeros in front fill the $n$ places. So each of the $2^n$ numbers gets at least one of the patterns. There are exactly $2^n$ patterns, and each pattern is the writing of only one number. If one number had two patterns, the $2^n$ numbers would use more than $2^n$ patterns, which do not exist. So each number has exactly one.

**Exercise 25.12 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-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 of Exercise 25.12.**

Read the text into a whole number (the doubling walk of [Listing 25.1](#lst-g8-binary-and-hexadecimal-to-decimal), with the base instead of 2), then write that number in the other base (repeated division):

```python
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))
```

*Any base to any base. code/grade-8/01-binary-and-hexadecimal/exercises/convert.py*

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.**

1. How many grains are on squares 1 to 8? Write each as a power of 2.
2. What is the total on the first 8 squares? Compare it with the number of grains on square 9.
3. Write the number of grains on square $k$ , and the total on the first 8 squares, in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) . Why is the total all ones?

**Part II — The whole board.**

```python
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())
```

***Listing 25.9.** All 64 squares. code/grade-8/01-binary-and-hexadecimal/listings/grains.py*

4. Why does the [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) `grains` double after it is added, and not before?
5. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) . How many grains are on the last square, and how many in total?
6. Check that the total is $2^{64} - 1$ , and explain why with the proposition of this chapter.
7. How many ones does the total have in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) ? How many [hexadecimal digits](#def-g8-binary-and-hexadecimal-hexadecimal) , and which?
8. 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.**

9. How many [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) does the total need?
10. A [counter](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#def-g6-while-loops-counter) of 32 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) counts the grains one by one. Up to which square can it count the total without running out of patterns?
11. How many [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) does a [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) need to count every grain of the board, from 0 to the total?
12. State the result.

**Solution of Problem 25.1.**

**1.** 1, 2, 4, 8, 16, 32, 64, 128: square $k$ holds $2^{k-1}$ grains.

**2.** $1 + 2 + \dots + 128 = 255$, one less than the 256 grains of square 9.

**3.** Square $k$ holds a 1 followed by $k - 1$ 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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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
```

***Output 25.8.** The rice on the board.*

The last square holds $2^{63}$ grains, more than nine billion billion, and the total is almost twice as much.

**6.** The total is $1 + 2 + \dots + 2^{63}$: in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), 64 ones. By the proposition, the largest number on 64 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) is $2^{64} - 1$; the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program)’s two lines agree.

**7.** 64 ones, so 16 groups of `1111`: sixteen `F`s.

**8.** About $1.8 \times 10^{19}$ grains of 25 milligrams make about $4.6 \times 10^{20}$ milligrams, that is about $4.6 \times 10^{11}$ tonnes: some 460 billion tonnes of rice.

**9.** 64 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), which is 8 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte).

**10.** 32 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) count up to $2^{32} - 1 = 4\,294\,967\,295$, which is exactly the total on the first 32 squares; the 33rd square goes past it.

**11.** 64 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit): the total is the largest number they can write.

**12.** **Result.** The board holds 18 446 744 073 709 551 615 grains, $2^{64} - 1$, written as sixteen `F`s in [hexadecimal](#def-g8-binary-and-hexadecimal-hexadecimal): exactly the largest number that 8 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) can hold.
