---
title: "Integers in the Machine"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 3
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 3 — Integers in the Machine

Noor’s grandfather kept an old step counter clipped to his belt. One summer he walked across a whole region, and each evening he wrote down the number it showed. On the eighth day the number was smaller than on the seventh, although he had walked all day. The counter was not broken. It had six digits on its little screen and, inside, a memory of a fixed number of bits; after the largest number it could hold, it went back to zero, like a car’s odometer.

Every number a processor works on lives in a fixed number of bits. This chapter shows how whole numbers, positive and negative, are written in $8$, $16$, $32$ or $64$ bits, what happens when a result does not fit, and how a program can work on the bits of a number one by one.

**You already know.**

A whole number is written in base $2$ with the digits $0$ and $1$, each position worth twice the one on its right; in base $16$ with the digits $0$ to $9$ and $A$ to $F$; Python’s `bin`, `hex` and `int(s, 2)` convert between bases, and two binary numbers are added column by column with a carry (Book 1, grade 8). A bit is one binary digit and a byte is eight bits (Book 1, grade 5). $2^{10} = 1024$, and $2^{a} \times 2^{b} =
2^{a+b}$ (mathematics book, grade 8).

## 3.1 Unsigned integers on $n$ bits

Base $2$ is one base among many. In any base $b \ge 2$, a whole number is written with digits from $0$ to $b - 1$, and the digit at position $i$ (counting from $0$ on the right) is worth $b^i$ times its value. The digits are found from the right by repeated division: the remainder of $n$ divided by $b$ is the last digit, and the quotient holds the others.

```python
DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"


def to_base(n, b):
    """Return the digits of the whole number n >= 0 in base b, 2 <= b <= 36."""
    if n == 0:
        return "0"
    digits = ""
    while n > 0:
        digits = DIGITS[n % b] + digits
        n = n // b
    return digits


for b in (2, 8, 10, 16, 36):
    print(f"2026 in base {b:2}: {to_base(2026, b)}")
print(int("11111101010", 2), int("7EA", 16))
```

***Listing 3.1.** Writing a number in any base from $2$ to $36$. code/grade-10/03-machine-integers/listings/to_base.py*

```
$ python to_base.py
2026 in base  2: 11111101010
2026 in base  8: 3752
2026 in base 10: 2026
2026 in base 16: 7EA
2026 in base 36: 1KA
2026 2026
```

***Output 3.1.** The same number in five bases. `int` reads a string of digits back in a given base.*

A processor does not write numbers with as many digits as needed: its registers and memory cells have a fixed size.

**Definition 3.1 (Unsigned integer, nnn-bit integer).**

An *$n$-bit integer* is a whole number stored in exactly $n$ bits, $b_{n-1} \dots b_1 b_0$. Read as an *unsigned integer*, its value is $b_{n-1} 2^{n-1} + \dots + b_1 2 + b_0$. The usual sizes are $8$ bits (one byte), $16$, $32$ and $64$ bits.

**Proposition 3.2 (Range of nnn bits).**

The [unsigned integers](#def-g10-machine-integers-unsigned) on $n$ bits are exactly the whole numbers from $0$ to $2^n - 1$. A whole number $x \ge 1$ needs $k$ bits, where $k$ is the number with $2^{k-1} \le x < 2^k$.

**Proof.** There are $2$ choices for each of the $n$ bits, so $2^n$ patterns, and different patterns have different values (base $2$ writing is unique). The smallest value is $0$ (all bits $0$). The largest has all bits $1$: adding $1$ to $11\dots1$ carries through every column and gives $100\dots0$, which is $2^n$; so $11\dots1$ is $2^n - 1$. Hence the $2^n$ values are $0, 1, \dots, 2^n - 1$. A number with $2^{k-1} \le x < 2^k$ fits in $k$ bits but not in $k - 1$, whose largest value is $2^{k-1} - 1$. ∎

So one byte holds $0$ to $255$, $16$ bits hold $0$ to $65{,}535$, and $32$ bits $0$ to $4{,}294{,}967{,}295$.

Python’s method `n.bit_length()` gives the number of bits that $n$ needs.

```python
for n in (1, 2, 255, 256, 1000, 65535, 65536):
    print(f"{n:6}  bit_length {n.bit_length():2}")

a = 2**20 - 1  # the largest number on 20 bits
b = 2**13 - 1  # the largest number on 13 bits
print("a + b needs", (a + b).bit_length(), "bits")
print("a * b needs", (a * b).bit_length(), "bits")
```

***Listing 3.2.** How many bits a number, a sum and a product need. code/grade-10/03-machine-integers/listings/bits_needed.py*

```
$ python bits_needed.py
     1  bit_length  1
     2  bit_length  2
   255  bit_length  8
   256  bit_length  9
  1000  bit_length 10
 65535  bit_length 16
 65536  bit_length 17
a + b needs 21 bits
a * b needs 33 bits
```

***Output 3.2.** Each power of two needs one more bit than the number just below it.*

**Proposition 3.3 (Bits of a sum and of a product).**

If $a$ fits in $p$ bits and $b$ in $q$ bits, with $p \ge q$, then $a + b$ fits in $p + 1$ bits and $a \times b$ fits in $p + q$ bits.

**Proof.** $a \le 2^p - 1$ and $b \le 2^q - 1 \le 2^p - 1$, so $a + b \le 2^{p+1} - 2 < 2^{p+1}$. And $a \times b \le (2^p - 1)(2^q - 1) < 2^p \times 2^q = 2^{p+q}$. ∎

The run above shows that both bounds can be reached: the largest numbers on $20$ and $13$ bits have a sum of $21$ bits and a product of $33$.

When a result needs more bits than the machine has, the extra bits are simply lost.

**Definition 3.4 (Overflow).**

An *overflow* happens when the result of an operation does not fit in the number of bits that hold it. An $n$-bit unsigned adder then keeps the $n$ lowest bits of the true result, that is, the remainder of the true result divided by $2^n$: the value *wraps around*.

Python’s `%` gives that remainder, so a few lines simulate the step counter, here with $16$ bits.

```python
def add_unsigned(a, b, n):
    """Add a and b as an n-bit unsigned adder does: keep the n lowest bits."""
    return (a + b) % 2**n


counter = 0
for step in range(65_540):
    counter = add_unsigned(counter, 1, 16)
    if step >= 65_533:
        print("after", step + 1, "steps the counter shows", counter)

print("8 bits:  250 + 10 =", add_unsigned(250, 10, 8))
print("16 bits: 250 + 10 =", add_unsigned(250, 10, 16))
```

***Listing 3.3.** A 16-bit counter, and one addition on $8$ and on $16$ bits. code/grade-10/03-machine-integers/listings/wrap.py*

```
$ python wrap.py
after 65534 steps the counter shows 65534
after 65535 steps the counter shows 65535
after 65536 steps the counter shows 0
after 65537 steps the counter shows 1
after 65538 steps the counter shows 2
after 65539 steps the counter shows 3
after 65540 steps the counter shows 4
8 bits:  250 + 10 = 4
16 bits: 250 + 10 = 260
```

***Output 3.3.** After $65{,}535$ comes $0$: a whole walk’s worth of steps has vanished.*

The toy machine of the next year (grade 11) has registers of one byte. The same addition, $250 + 10$, run on it:

```text
        LOADI R0, 250
        ADDI R0, 10     ; 250 + 10 does not fit in one byte
        HALT
```

***Listing 3.4.** Three instructions for the toy machine. code/grade-10/03-machine-integers/listings/toy_wrap.toy*

```
$ python -m toymachine run toy_wrap.toy --dump
R0=4 R1=0 R2=0 R3=0 PC=4 SP=0 Z=0 N=0 C=1
  M[0]=4  M[1]=250  M[2]=24  M[3]=10
```

***Output 3.4.** Register `R0` holds $4$, and the flag `C` (carry) is $1$: the machine kept the lost bit in a flag.*

The processor does not stop at an [overflow](#def-g10-machine-integers-overflow); it records it in its carry flag, and a program that does not look at the flag never knows.

## 3.2 Signed integers: two’s complement

Negative numbers need a sign, but a memory cell holds only bits. The usual method gives the leftmost bit a negative weight.

**Definition 3.5 (Two’s complement).**

In *two’s complement* on $n$ bits, the pattern $b_{n-1} b_{n-2} \dots b_0$ stands for the signed value

$$
-b_{n-1} 2^{n-1} + b_{n-2} 2^{n-2} + \dots + b_1 2 + b_0 .
$$

The leftmost bit is the *sign bit*: it is $1$ exactly for the negative values.

![The weights of the bits of one byte in two’s complement. Only the leftmost weight is negative; the byte of eight 1 bits stands for -1.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-machine-integers/fig-6931ac4f8b52.svg)

*The weights of the bits of one byte in [two’s complement](#def-g10-machine-integers-twos-complement). Only the leftmost weight is negative; the byte of eight $1$ bits stands for $-1$.*

The first half of the patterns, those starting with $0$, keep their unsigned value; the second half stands for negative numbers. The listing prints the sixteen patterns of $4$ bits.

```python
def encode(x, n):
    """Return the n-bit two's complement pattern of x as an unsigned number.

    Precondition: -2**(n-1) <= x < 2**(n-1).
    """
    return x % 2**n


def decode(u, n):
    """Return the signed value of the n-bit pattern u, 0 <= u < 2**n."""
    if u >= 2 ** (n - 1):
        return u - 2**n
    return u


for u in range(16):
    print(f"{u:04b}  unsigned {u:2}  signed {decode(u, 4):3}")
print("encode(-3, 8) =", format(encode(-3, 8), "08b"))
```

***Listing 3.5.** Encoding and decoding $n$-bit [two’s complement](#def-g10-machine-integers-twos-complement). code/grade-10/03-machine-integers/listings/twos.py*

```
$ python twos.py
0000  unsigned  0  signed   0
0001  unsigned  1  signed   1
0010  unsigned  2  signed   2
0011  unsigned  3  signed   3
0100  unsigned  4  signed   4
0101  unsigned  5  signed   5
0110  unsigned  6  signed   6
0111  unsigned  7  signed   7
1000  unsigned  8  signed  -8
1001  unsigned  9  signed  -7
1010  unsigned 10  signed  -6
1011  unsigned 11  signed  -5
1100  unsigned 12  signed  -4
1101  unsigned 13  signed  -3
1110  unsigned 14  signed  -2
1111  unsigned 15  signed  -1
encode(-3, 8) = 11111101
```

***Output 3.5.** On $4$ bits, from $-8$ to $7$. The unsigned and the signed reading differ by $16$ in the second half.*

**Proposition 3.6 (Range and negation).**

The signed integers on $n$ bits are the whole numbers from $-2^{n-1}$ to $2^{n-1} - 1$. The pattern of $x$ and its unsigned reading $u$ satisfy $u = x$ if $x \ge 0$ and $u = x + 2^n$ if $x < 0$. To negate a number, flip every bit and add $1$ (keeping $n$ bits).

**Proof.** If the sign bit is $0$, the value is that of the other $n - 1$ bits, from $0$ to $2^{n-1} - 1$. If it is $1$, the value is $-2^{n-1}$ plus a number from $0$ to $2^{n-1} - 1$, so from $-2^{n-1}$ to $-1$; and it is the unsigned value, which counts the leftmost bit as $+2^{n-1}$, minus $2 \times 2^{n-1} = 2^n$. For the negation, write $\bar x$ for the pattern with every bit of $x$ flipped. In each column exactly one of $x$ and $\bar x$ has a $1$, so the unsigned readings add up to $11\dots1 = 2^n - 1$. Hence $\bar x + 1 = 2^n - x$, which on $n$ bits is the pattern of $-x$. ∎

**Example 3.7 (−5-5−5 on 8 bits).**

$5$ is `00000101`; flipping every bit gives `11111010`; adding $1$ gives `11111011`. Check: $-128 + 64 + 32 + 16 + 8 + 2 + 1 = -5$.

![The sixteen patterns of 4 bits on a wheel, with their signed values. Adding 1 moves one step clockwise. The signed overflow is the step from 7 to -8; the unsigned one is the step from 15 (that is, -1) to 0.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-machine-integers/fig-8f44c4242139.svg)

*The sixteen patterns of $4$ bits on a wheel, with their signed values. Adding $1$ moves one step clockwise. The signed [overflow](#def-g10-machine-integers-overflow) is the step from $7$ to $-8$; the unsigned one is the step from $15$ (that is, $-1$) to $0$.*

The great advantage of [two’s complement](#def-g10-machine-integers-twos-complement) is that the addition does not change. Since a negative $x$ is stored as $x + 2^n$, and the adder works modulo $2^n$, the unsigned adder of the previous section adds signed numbers correctly as long as the true result is in the range. One circuit serves both; grade 11 builds it from gates.

When the true signed result is out of range, the result wraps around the wheel and the sign comes out wrong: $100 + 50$ on $8$ bits gives the pattern of $150$, which reads as $-106$. This can be spotted without the true result.

**Proposition 3.8 (Detecting a signed overflow).**

The sum of two signed $n$-bit integers [overflows](#def-g10-machine-integers-overflow) exactly when the two operands have the same sign and the result’s sign bit is different.

The proof is [Exercise 3.14](#exo-g10-machine-integers-14).

## 3.3 Working on the bits

**Definition 3.9 (Bitwise operation).**

A *bitwise operation* works on each bit position separately. In Python, `a & b` has a $1$ where both `a` and `b` have a $1$ (and ); `a | b` where at least one has a $1$ (or ); `a ^ b` where exactly one has a $1$ (exclusive or, xor ); and `~a` flips every bit (not ; for Python’s integers, `~a` equals `-a - 1`).

**Definition 3.10 (Shift).**

A *shift* moves every bit of a number by $k$ positions: `a << k` to the left, adding $k$ zeros on the right, and `a >> k` to the right, dropping the $k$ rightmost bits. For a whole number $a \ge 0$, `a << k` is $a \times 2^k$ and `a >> k` is the quotient `a // 2**k`.

The most common use of these operations is to pick out, switch on or switch off one bit, using a second number that has $1$ bits only at the places of interest.

**Definition 3.11 (Mask).**

A *mask* is a number used with a [bitwise operation](#def-g10-machine-integers-bitwise) to select some bits of another number: `x & m` keeps the bits of `x` where `m` has a $1$ and clears the others; `x | m` sets them to $1$; `x ^ m` flips them. The mask `1 << i` has a single $1$, at position $i$.

![Clearing bit 5 of x (bits are numbered from 0 on the right). The mask has a 0 at position 5 and 1 elsewhere; copies every bit of x except that one.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-machine-integers/fig-147309a94d3d.svg)

*Clearing bit $5$ of `x` (bits are numbered from $0$ on the right). The [mask](#def-g10-machine-integers-mask) has a $0$ at position $5$ and $1$ elsewhere; and copies every bit of `x` except that one.*

```python
flags = 0b1010_0110

print(format(flags, "08b"), "bit 2 is", (flags >> 2) & 1)
print(format(flags | (1 << 0), "08b"), "after setting bit 0")
print(format(flags & ~(1 << 5), "08b"), "after clearing bit 5")
print(format(flags ^ 0b1111_1111, "08b"), "after flipping every bit")

colour = 0xF4A261  # a sandy orange, as on a web page
red = (colour >> 16) & 0xFF
green = (colour >> 8) & 0xFF
blue = colour & 0xFF
print("red", red, "green", green, "blue", blue)
print(hex((red << 16) | (green << 8) | blue))
```

***Listing 3.6.** [Masks](#def-g10-machine-integers-mask) on a byte of flags, and the three bytes of a colour. code/grade-10/03-machine-integers/listings/masks.py*

```
$ python masks.py
10100110 bit 2 is 1
10100111 after setting bit 0
10000110 after clearing bit 5
01011001 after flipping every bit
red 244 green 162 blue 97
0xf4a261
```

***Output 3.6.** `format(x, "08b")` writes `x` in binary on eight digits. The colour splits into three bytes, and the three bytes give the colour back.*

A colour on a screen is often stored as $24$ bits, one byte for each of red, green and blue (Book 1 showed the `#F4A261` notation of web pages). A [shift](#def-g10-machine-integers-shift) moves the wanted byte to the right end, and the [mask](#def-g10-machine-integers-mask) `0xFF`, eight $1$ bits, keeps that byte alone.

![The colour 0xF4A261 as three bytes. Red is (c >> 16) & 0xFF, green (c >> 8) & 0xFF, blue c & 0xFF.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-machine-integers/fig-680c571b4703.svg)

*The colour `0xF4A261` as three bytes. Red is `(c >> 16) & 0xFF`, green `(c >> 8) & 0xFF`, blue `c & 0xFF`.*

**Method 3.12 (Testing, setting and clearing bit iii).**

1. Test: `(x >> i) & 1` is $1$ when bit $i$ of `x` is $1$ .
2. Set to $1$ : `x | (1 << i)` .
3. Clear to $0$ : `x & ~(1 << i)` .
4. Flip: `x ^ (1 << i)` .

## 3.4 Integers that never overflow

Python hides all of this: its integers have unlimited precision. When a result does not fit in a machine word, Python uses as many words as needed, at the price of slower arithmetic on very large numbers.

```python
import math

print(2**100)
print(math.factorial(30))
print((2**100).bit_length(), math.factorial(30).bit_length())
print(2**63 - 1 + 1)
```

***Listing 3.7.** Large integers in Python. code/grade-10/03-machine-integers/listings/big_int.py*

```
$ python big_int.py
1267650600228229401496703205376
265252859812191058636308480000000
101 108
9223372036854775808
```

***Output 3.7.** $2^{100}$ needs $101$ bits; the last line goes past the largest signed $64$-bit integer without any trouble.*

**In practice — Fixed widths in other languages.**

Most other languages, among them C, C++, Rust and Java, use the processor’s fixed widths. The C type `int32_t`, for instance, is a signed integer of exactly $32$ bits; adding $1$ to the largest one is an error that the program may not notice. When code in those languages computes with large values (money in cents, times in microseconds, file sizes), the first question is always: how many bits does the largest value need? The university books meet these types.

**History — The year 2038.**

Many systems count time as a number of seconds since an instant called the *Epoch*, fixed by the POSIX standard at 1 January 1970, 00:00:00 UTC, every day counting exactly $86{,}400$ seconds. A count of seconds kept in a signed $32$-bit integer runs out in 2038, and the weekend problem computes the exact second. Software written to count in $64$ bits does not have the problem; old devices and old file formats that store $32$ bits do, which is why the date is known as the year 2038 problem.

## 3.5 Exercises

**Exercise 3.1 ★.**

What do `bin(13)`, `hex(255)`, `int("1010", 2)`, `int("ff", 16)` and `bin(2**8)` return?

**Solution of Exercise 3.1.**

(Python prints them with single quotes.) `"0b1101"`, `"0xff"`, `10`, `255` and `"0b100000000"` ($2^8 = 256$ needs nine bits).

**Exercise 3.2 ★.**

A sensor sends its readings as $12$-bit [unsigned integers](#def-g10-machine-integers-unsigned). What are the smallest and the largest values? How many different values can it send?

**Solution of Exercise 3.2.**

From $0$ to $2^{12} - 1 = 4095$: $4096$ different values.

**Exercise 3.3 ★.**

Write $-5$, $-1$, $-128$ and $127$ in [two’s complement](#def-g10-machine-integers-twos-complement) on $8$ bits. Which of $128$ and $-129$ can be written, and why?

**Solution of Exercise 3.3.**

$-5$ is `11111011` (see the example of the chapter), $-1$ is `11111111`, $-128$ is `10000000`, $127$ is `01111111`. Neither $128$ nor $-129$ can be written: the range on $8$ bits is $-128$ to $127$.

**Exercise 3.4 ★.**

What do `1 << 10`, `100 >> 2`, `7 >> 3`, `5 << 1` and `0b1011 >> 1` give? Say each time which multiplication or division by a power of two it computes.

**Solution of Exercise 3.4.**

`1 << 10` is $1024 = 1 \times 2^{10}$; `100 >> 2` is $25$, the quotient of $100$ by $4$; `7 >> 3` is $0$, the quotient of $7$ by $8$; `5 << 1` is $10 = 5 \times 2$; `0b1011 >> 1` is `0b101`, that is $5$, the quotient of $11$ by $2$.

**Exercise 3.5 ★.**

Without looking at the chapter’s listing, write `to_base(n, b)` with its [docstring](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-docstring) and test it by converting back with `int`. What does it return for $n = 0$, and why must that case be treated apart?

**Solution of Exercise 3.5.**

The function of the chapter’s listing. For $n = 0$ it returns `"0"`; without the special case, the loop `while n > 0` would not run and the function would return the empty string, which is not a way of writing a number. The test: `int(to_base(n, b), b) == n` for many `n` and `b` (the chapter’s tests try $500$).

**Exercise 3.6 ★★.**

Without computing the product, give the largest number of bits that the product of a $20$-bit number and a $13$-bit number can need, and the smallest. Give an example for each.

**Solution of Exercise 3.6.**

At most $20 + 13 = 33$ bits, by the proposition on the bits of a product; the largest numbers on $20$ and $13$ bits reach it, as the listing printed. At least $32$ bits: a $20$-bit number is at least $2^{19}$ and a $13$-bit number at least $2^{12}$, so the product is at least $2^{31}$, which needs $32$ bits; $2^{19} \times 2^{12}$ is an example.

**Exercise 3.7 ★★.**

A program reads 8-bit two’s-complement values from a file as strings of eight characters `0` and `1`, and decodes them with `int(bits, 2)`. A temperature of $-5$ degrees appears as $251$. Explain the bug and write a correct `decode(bits)`.

**Solution of Exercise 3.7.**

`int(bits, 2)` gives the leftmost bit the weight $+128$ instead of $-128$, that is, it returns the unsigned reading, which is $256$ too large for a negative value: $-5 + 256 = 251$. A correct decoder subtracts $2^8$ when the sign bit is $1$: `u = int(bits, 2)`, then `return u - 2**len(bits) if bits[0] == "1" else u` (`exercises/decode_bug.py`).

**Exercise 3.8 ★★.**

Write `test_bit(x, i)`, `set_bit(x, i)` and `clear_bit(x, i)`, and test that clearing a bit after setting it gives the same result as clearing it directly.

**Solution of Exercise 3.8.**

The three functions of the method box (`exercises/bit_ops.py`): `(x >> i) & 1 == 1`, `x | (1 << i)` and `x & ~(1 << i)`. Clearing after setting gives the same result as clearing directly, since the clear decides bit `i` alone and setting changed no other bit; the chapter’s tests check it on $300$ random pairs.

**Exercise 3.9 ★★.**

On $8$ bits, compute $100 + 50$: the pattern of the result, its unsigned value and its signed value. Which of the two readings [overflows](#def-g10-machine-integers-overflow)? Do the same for $-100 + (-50)$.

**Solution of Exercise 3.9.**

$100 + 50 = 150$: the pattern is `10010110`. Its unsigned value is $150$, which fits (no carry); its signed value is $150 - 256 = -106$: the signed reading [overflows](#def-g10-machine-integers-overflow). For $-100 + (-50)$, the patterns are $156$ and $206$, whose sum $362$ leaves the pattern $362 - 256 = 106$, `01101010`: the unsigned addition carries, and the signed result reads $106$ instead of $-150$, so both readings [overflow](#def-g10-machine-integers-overflow).

**Exercise 3.10 ★★.**

Follow the values of `a` and `b` through `a = a ^ b`, `b = a ^ b`, `a = a ^ b`, starting with `a = 12` and `b = 10`, in binary. What do the three lines do? Use the facts `x ^ x == 0` and `x ^ 0 == x` to explain why.

**Solution of Exercise 3.10.**

`a = 1100`, `b = 1010`. After the first line `a = 0110`; after the second `b = 0110 ^ 1010 = 1100`; after the third `a = 0110 ^ 1100 = 1010`. Now `a` is $10$ and `b` is $12$: the values are swapped. With $a_0$, $b_0$ the starting values, the second line computes $(a_0 \oplus b_0) \oplus b_0 = a_0 \oplus 0 = a_0$, and the third $(a_0 \oplus b_0) \oplus a_0 = b_0$, writing $\oplus$ for xor (it can be computed in any order, as one checks bit by bit).

**Exercise 3.11 ★★.**

To read the green byte of a colour, a student writes `(c >> 16) & 0xFF`; another writes `c >> 8`. For `c = 0xF4A261`, what does each get? Correct both.

**Solution of Exercise 3.11.**

`(c >> 16) & 0xFF` is `0xF4` $= 244$, the red byte. `c >> 8` is `0xF4A2` $= 62{,}626$, the red and green bytes together. Green is `(c >> 8) & 0xFF` $= 162$: [shift](#def-g10-machine-integers-shift) by one byte, then keep one byte.

**Exercise 3.12 ★★★.**

Prove that for every signed $n$-bit integer $x$ other than $-2^{n-1}$, flipping the bits of $x$ and adding $1$ gives the pattern of $-x$, and say what happens for $-2^{n-1}$ (try it on $4$ bits).

**Solution of Exercise 3.12.**

Let $u$ be the unsigned reading of $x$ and $\bar u$ that of the flipped pattern. In each column one of the two has a $1$, so $u + \bar u = 2^n - 1$ and $\bar u + 1 = 2^n - u$. If $x \ge 0$ then $u = x$ and $2^n - x$ is the pattern of $-x$ (for $x = 0$ it is $2^n$, which keeps $n$ bits as $0$). If $x < 0$ then $u = x + 2^n$ and $2^n - u = -x$, which is positive and in range as long as $x \ne -2^{n-1}$. For $x = -2^{n-1}$ (on $4$ bits, `1000`, that is $-8$), flipping gives `0111` and adding $1$ gives `1000` again: $-(-8) = 8$ is out of range, and the negation [overflows](#def-g10-machine-integers-overflow) back to $-8$.

**Exercise 3.13 ★★★.**

The *population count* of $x \ge 0$ is the number of $1$ bits of $x$. Write a function that looks at the bits one by one with `x & 1` and `x >> 1`, and a second one that repeats `x = x & (x - 1)` until $x$ is $0$. Explain why `x & (x - 1)` clears the rightmost $1$ bit, and compare the numbers of loop turns of the two functions for $x = 2^{40}$.

**Solution of Exercise 3.13.**

Subtracting $1$ turns the rightmost $1$ bit of $x$ into $0$ and the $0$ bits to its right into $1$; the bits further left do not change. The and with $x$ keeps those left bits and clears all the others, that is, it clears exactly the rightmost $1$. So the second function turns its loop once per $1$ bit, while the first turns once per bit of $x$ (`x.bit_length()` times). For $x = 2^{40}$: $41$ turns against $1$ (`exercises/popcount.py`).

**Exercise 3.14 ★★★.**

Prove the proposition on detecting a signed [overflow](#def-g10-machine-integers-overflow): if $x$ and $y$ have different signs, $x + y$ is always in range; if both are $\ge 0$ and the true sum is too large, the stored result has its sign bit set; if both are negative and the true sum is too small, it has its sign bit clear.

**Solution of Exercise 3.14.**

If $x \ge 0 > y$, then $y \le x + y < x$, so the sum lies between two numbers in range and is in range. If both are $\ge 0$, the true sum is at most $2(2^{n-1} - 1) = 2^n - 2$; when it is too large, it lies from $2^{n-1}$ to $2^n - 2$, fits in $n$ unsigned bits, and its bit $n-1$ is $1$: the stored result reads as negative. If both are negative, the true sum is at least $-2^n$; when it is too small, it lies from $-2^n$ to $-2^{n-1} - 1$, and the stored pattern, the true sum plus $2^n$, lies from $0$ to $2^{n-1} - 1$: its sign bit is $0$. Conversely, when there is no [overflow](#def-g10-machine-integers-overflow) the result has the sign of two operands of the same sign.

**Exercise 3.15 ★★★.**

Write `add_n_bits(a, b, n)`, which adds two $n$-bit patterns and returns the $n$-bit result, the carry (the unsigned sum needed $n + 1$ bits) and the signed [overflow](#def-g10-machine-integers-overflow) flag. Test it against Python’s own arithmetic for every pair of $8$-bit values you can afford, and give the result for `(100, 50, 8)`.

**Solution of Exercise 3.15.**

The file `exercises/add_n_bits.py` computes `total = a + b`, `result = total % 2**n`, `carry = total >= 2**n`, and with `sign = 2**(n - 1)`, the [overflow](#def-g10-machine-integers-overflow) flag is true when `a & sign == b & sign` and `result & sign != a & sign` (the proposition proved in the previous exercise). The tests compare it with Python’s arithmetic on $256 \times 37$ pairs of $8$-bit values. `add_n_bits(100, 50, 8)` returns `(150, False, True)`.

## 3.6 Problem: The 2038 Rollover

**Problem 3.1.**

Weekend problem — the last second of a 32-bit clock

A door-entry system records the time of each badge as the number of seconds since 1 January 1970, 00:00:00 UTC (see the history box of this chapter), in a signed $32$-bit integer. The program `exercises/rollover.py` and Python’s `datetime` module help with the dates, but every count below can be done by hand first.

**Part I — Counting seconds.**

1. How many seconds are there in a day, and in a year of $365$ days?
2. How many days are there from 1 January 1970 to 1 January 2000? (There are $7$ leap years among 1970–1999; name them.)
3. Deduce the number of seconds since the Epoch at 1 January 2000, 00:00:00 UTC.
4. Check it with Python: `datetime(2000, 1, 1, tzinfo=UTC).timestamp()` , after `from datetime import UTC, datetime` .

**Part II — The largest value.**

5. What is the largest signed $32$ -bit integer? Give it as a power of two minus one and in decimal.
6. Write its pattern in hexadecimal.
7. About how many years of $365.25$ days does it represent?
8. Add that to 1970: in which year does the counter run out?

**Part III — The exact instant.**

9. Run `exercises/rollover.py` . At which date and time does the largest value fall?
10. How many whole days after the Epoch is that, and how many seconds remain after those days?
11. Convert the remaining seconds into hours, minutes and seconds, and check the time printed by the program.
12. What is the next second, written as a count, and why can the register not hold it?

**Part IV — After the wrap.**

13. Adding $1$ to the largest value in a signed $32$ -bit register gives which pattern, and which signed value?
14. Using the wheel of this chapter, explain the jump on a $4$ -bit clock that counts from $0$ .
15. Which date does the program print for the wrapped value?
16. By how many seconds does the clock jump backwards? Express it as a power of two.
17. How long before 1970 is the wrapped date, in days? Check with the answer to question 10.
18. If the count were stored as an *unsigned* $32$ -bit integer instead, when would it run out? (The program prints it.) What would the system then be unable to record?
19. With $64$ signed bits, how long would the count last? (The program prints it.)
20. State the result: the last instant a signed $32$ -bit count of seconds can hold, and the date it shows one second later.

**Solution of Problem 3.1.**

**1.** $24 \times 3600 = 86{,}400$ seconds in a day; $365 \times 86{,}400 = 31{,}536{,}000$ in a year of $365$ days.

**2.** The leap years are 1972, 1976, 1980, 1984, 1988, 1992 and 1996: $30 \times 365 + 7 = 10{,}957$ days.

**3.** $10{,}957 \times 86{,}400 = 946{,}684{,}800$ seconds.

**4.** Python prints `946684800.0`.

**5.** $2^{31} - 1 = 2{,}147{,}483{,}647$.

**6.** `0x7FFFFFFF`: a $0$ sign bit followed by $31$ ones.

**7.** A year of $365.25$ days lasts $31{,}557{,}600$ seconds; $2{,}147{,}483{,}647 / 31{,}557{,}600 \approx 68.05$ years.

**8.** $1970 + 68 = 2038$.

**9.** 19 January 2038, 03:14:07 UTC.

**10.** $2{,}147{,}483{,}647 = 24{,}855 \times 86{,}400 + 11{,}647$: $24{,}855$ whole days and $11{,}647$ seconds.

**11.** $11{,}647 = 3 \times 3600 + 14 \times 60 + 7$: 03:14:07, as printed.

**12.** $2^{31} = 2{,}147{,}483{,}648$, one more than the largest signed $32$-bit integer.

**13.** The pattern written `0x80000000` in hexadecimal, a $1$ followed by $31$ zeros, whose signed value is $-2^{31} = -2{,}147{,}483{,}648$.

**14.** On the $4$-bit wheel, the clock counts $0, 1, \dots, 7$, then the next step lands on $-8$: it jumps from the largest value to the smallest.

**15.** 13 December 1901, 20:45:52 UTC.

**16.** The register holds $-2^{31}$ instead of $2^{31}$: the clock is $2^{32} = 4{,}294{,}967{,}296$ seconds behind the true time.

**17.** $2^{31} = 24{,}855 \times 86{,}400 + 11{,}648$, one second more than in question 10. Going back $24{,}855$ days from 1 January 1970 reaches 14 December 1901, 00:00:00, and going back $11{,}648$ seconds more, that is 3 h 14 min 8 s, reaches 13 December 1901, 20:45:52.

**18.** At $2^{32} - 1$ seconds: 7 February 2106, 06:28:15 UTC. An unsigned count cannot hold any negative value, so it could not record a date before 1970.

**19.** About $292$ billion years.

**20.** A signed $32$-bit count of seconds since 1 January 1970 holds its last value, $2^{31} - 1$, at 19 January 2038, 03:14:07 UTC; one second later it wraps to $-2^{31}$, which reads as 13 December 1901, 20:45:52 UTC.
