---
title: Number formats lab
heading: Two's complement, flags, floats, Gray code and fixed point, in Python
eyebrow: C7 · Lesson 22 · Number formats lab
xp: 50
---

::: hook
Every number a digital circuit handles is a pattern of bits with an agreed meaning, and most bugs at the hardware-software boundary are disagreements about that meaning: a value read as unsigned that was meant as signed, an overflow nobody checked, a float compared for exact equality, a fixed-point product that wrapped instead of saturating. In this lab you'll write the conversions and the flag logic of a processor's adder, take floats apart into their fields, and build fixed-point arithmetic that saturates.

::: play
- The staircase is the spacing between neighboring single-precision floats, against the value itself, both on log scales.
- The spacing doubles at every power of two: floats keep about the same relative precision, about 1 part in 8 million, everywhere.
- Compare with fixed point, whose spacing is the same for every value: fine for large numbers, coarse relative to small ones.
:::
:::

```sim plot
view: graph
x: x = 0.001..10000 log
y: s = 1e-12..0.01 log
slider: q = 8..30 step 1 = 15
plot: 2^(floor(log(x)/log(2)) - 23) | label: float spacing | samples: 600
plot: 2^(-q) | color: ch2 | label: fixed-point spacing, q fraction bits | samples: 2
readout: float relative precision = 2^(-23) | digits: 3
```

::: predict
## A program adds 0.1 to a float ten times and compares the result with 1.0. Is it equal?

- [ ] Yes, exactly
- [x] Not necessarily: 0.1 has no exact binary form, and each addition rounds
- [ ] No, it's off by about 10%
- [ ] It depends on the processor's speed

::: reveal
Not necessarily. 0.1 in binary is a repeating fraction, 0.000110011..., so the stored value is slightly off, and each addition rounds again. In single precision the sum comes out as 1.0000001 instead of 1. Floats should be compared with a tolerance, not for equality.
:::
:::

::: nameit
## Two's complement and flags

An n-bit pattern means $-2^{n-1}b_{n-1} + \sum_{i<n-1}2^ib_i$ in two's complement. An adder sets four flags:

- **C** (carry): the carry out of the top bit, an unsigned overflow;
- **V** (overflow): the operands have the same sign and the result the other, a signed overflow, $C_n \oplus C_{n-1}$;
- **Z** (zero) and **N** (negative, the top bit).

## IEEE 754 single precision

1 sign bit, 8 exponent bits with a bias of 127, and 23 fraction bits with a hidden leading 1: $(-1)^s \times 1.f \times 2^{e - 127}$. Python's `struct` module packs a float into its 4 bytes and back.

## Fixed point

A **Q-format** value with q fraction bits stores $x \times 2^q$ as an integer. A product of two Q15 numbers has 30 fraction bits; shifting right by 15 (with rounding) returns it to Q15. Results outside the range should **saturate** at the largest or smallest value instead of wrapping, which turns an overflow into a small error instead of a sign flip.
:::

::: example
## Add 0x70 and 0x30 in an 8-bit adder. What are the result and the four flags?

::: solution
1. **Add.**
   $$\begin{aligned} 112 + 48 &= 160 \\ &= \text{0xA0} \end{aligned}$$
2. **Carry.** No carry out of bit 7, so C = 0.
3. **Overflow.** Both operands are positive but the result's top bit is 1, so V = 1: as signed numbers, 112 + 48 gave −96.
4. **Zero and negative.** Z = 0 and N = 1.
5. **Read it both ways.** An unsigned program sees 160, correct; a signed one sees an overflow it must handle.
6. **What the flags are for.** The adder computes one pattern; the flags let either reading check it.

**Answer:** 0xA0 (160), with C = 0, V = 1, Z = 0 and N = 1.
:::
:::

::: example
## Pack 6.5 and −12.5 as single-precision floats and read back their fields.

::: solution
1. **Pack 6.5.**
   $$6.5 = 1.101_2 \times 2^2$$
   so s = 0, e = 129, f = 0.625: 0x40D00000.
2. **Pack −12.5.**
   $$-12.5 = -1.5625 \times 2^3$$
   so s = 1, e = 130, f = 0.5625: 0xC1480000.
3. **Unpack.** Unpacking 0xC1480000 gives back exactly −12.5, since both values have short binary fractions.
4. **A value that doesn't fit.** A value like 0.1 doesn't, and unpacking its pattern gives 0.100000001490116.

**Answer:** 6.5 is 0x40D00000 (s = 0, e = 129, f = 0.625) and −12.5 is 0xC1480000 (s = 1, e = 130, f = 0.5625); both read back exactly.
:::
:::

::: example
## Multiply 0.75 by 0.5 in Q15, then multiply −1 by −1.

::: solution
1. **Convert to Q15.** 0.75 is 24576 and 0.5 is 16384.
2. **Multiply.**
   $$\begin{aligned} &24576 \times 16384 \\ &= 402\,653\,184 \end{aligned}$$
   with 30 fraction bits.
3. **Round and shift.** Adding half a step and shifting right by 15 gives 12288, which is 0.375.
4. **Square −1.** In Q15, −1 is −32768, and its square, shifted, would be +32768: one more than the largest Q15 value, 32767.
5. **Wrap or saturate.** Wrapping would give −1, the wrong sign; saturating gives 32767, about 0.99997.
6. **In hardware.** DSP processors saturate in hardware for exactly this case.

**Answer:** 0.75 × 0.5 gives 12288, which is 0.375; −1 × −1 gives +32768, which saturates to 32767 (about 0.99997).
:::
:::

::: check
kind: python

## Step 1. Write `to_signed(x, n)` returning the value of the n-bit pattern x read as two's complement, and `to_bits(v, n)` returning the n-bit pattern (as a non-negative integer) for the value v.

```python starter
def to_signed(x, n):
    return x

def to_bits(v, n):
    return v

print(to_signed(0xB6, 8), to_bits(-45, 8))
```

```python solution
def to_signed(x, n):
    x &= (1 << n) - 1
    return x - (1 << n) if x >> (n - 1) else x

def to_bits(v, n):
    return v & ((1 << n) - 1)

print(to_signed(0xB6, 8), to_bits(-45, 8))
```

```python tests
assert to_signed(0xB6, 8) == -74 and to_bits(-45, 8) == 0xD3, "0xB6 is −74; −45 is 0xD3."
assert all(to_signed(to_bits(v, 12), 12) == v for v in range(-2048, 2048)), "The two must invert each other over the whole 12-bit range."
assert to_signed(0x7F, 8) == 127 and to_signed(0x80, 8) == -128, "The range ends."
```

::: right
Right. Masking with $2^n - 1$ is all the hardware does; the meaning is in how you read the top bit.
:::
:::

::: check
kind: python

## Step 2. Write `add_flags(a, b, n)` for n-bit patterns a and b, returning `(result, C, V, Z, N)`.

```python starter
def add_flags(a, b, n):
    r = (a + b) % (1 << n)
    return r, 0, 0, int(r == 0), 0

print(add_flags(0x70, 0x30, 8))
```

```python solution
def add_flags(a, b, n):
    mask = (1 << n) - 1
    total = (a & mask) + (b & mask)
    r = total & mask
    C = total >> n
    sa, sb, sr = (a >> (n - 1)) & 1, (b >> (n - 1)) & 1, (r >> (n - 1)) & 1
    V = int(sa == sb and sr != sa)
    return r, C, V, int(r == 0), sr

print(add_flags(0x70, 0x30, 8))
```

```python tests
assert add_flags(0x70, 0x30, 8) == (0xA0, 0, 1, 0, 1), "112 + 48: signed overflow."
assert add_flags(0x9C, 0xCE, 8) == (0x6A, 1, 1, 0, 0), "−100 + −50: carry and overflow."
assert add_flags(0xFF, 0x01, 8) == (0, 1, 0, 1, 0), "−1 + 1 = 0 with a carry, no overflow."
```

::: right
Right. C and V answer different questions about the same sum.
:::
:::

::: check
kind: python

## Step 3. Write `float_fields(x)` returning `(s, e, f)`: the sign bit, the biased exponent and the fraction (as a number between 0 and 1) of x stored as an IEEE single, and `float_bits(x)` returning its 32-bit pattern as an integer.

```python starter
def float_bits(x):
    return 0

def float_fields(x):
    return 0, 127, 0.0

print(hex(float_bits(6.5)), float_fields(-12.5))
```

```python solution
import struct

def float_bits(x):
    return struct.unpack('>I', struct.pack('>f', x))[0]

def float_fields(x):
    b = float_bits(x)
    return b >> 31, (b >> 23) & 0xFF, (b & 0x7FFFFF) / 2 ** 23

print(hex(float_bits(6.5)), float_fields(-12.5))
```

```python tests
assert float_bits(6.5) == 0x40D00000 and float_bits(-12.5) == 0xC1480000, "6.5 and −12.5."
assert float_fields(-12.5) == (1, 130, 0.5625), f"Expected (1, 130, 0.5625); got {float_fields(-12.5)}"
s, e, f = float_fields(0.1)
assert (s, e) == (0, 123) and abs((1 + f) * 2 ** (e - 127) - 0.100000001490116) < 1e-15, "0.1 is stored as 0.100000001490116."
```

::: right
Right. The fields recombine as $(-1)^s(1 + f)2^{e - 127}$.
:::
:::

::: check
kind: python

## Step 4. Write `gray(b)` and `from_gray(g)` converting between binary and Gray code for non-negative integers.

```python starter
def gray(b):
    return b

def from_gray(g):
    return g

print(gray(13), from_gray(11))
```

```python solution
def gray(b):
    return b ^ (b >> 1)

def from_gray(g):
    b = 0
    while g:
        b ^= g
        g >>= 1
    return b

print(gray(13), from_gray(11))
```

```python tests
assert gray(13) == 11 and from_gray(11) == 13, "13 is 1011 in Gray code."
assert all(from_gray(gray(v)) == v for v in range(4096)), "They must invert each other."
assert all(bin(gray(v) ^ gray(v + 1)).count('1') == 1 for v in range(4095)), "Neighbors differ in one bit."
```

::: right
Right. The running XOR undoes the shifted XOR.
:::
:::

::: check
kind: python

## Step 5. Write `q15_mul(a, b)` multiplying two Q15 integers (−32768 to 32767) with round-to-nearest and saturation.

```python starter
def q15_mul(a, b):
    return (a * b) >> 15

print(q15_mul(24576, 16384), q15_mul(-32768, -32768))
```

```python solution
def q15_mul(a, b):
    p = (a * b + (1 << 14)) >> 15
    return max(-32768, min(32767, p))

print(q15_mul(24576, 16384), q15_mul(-32768, -32768))
```

```python tests
assert q15_mul(24576, 16384) == 12288, "0.75 × 0.5 = 0.375."
assert q15_mul(-32768, -32768) == 32767, "−1 × −1 saturates at 32767."
assert q15_mul(1, 16384) == 1 and q15_mul(-32768, 32767) == -32767, "Rounding and the other end."
```

::: right
Right. Rounding halves the error of a plain shift; saturating keeps the sign right.
:::
:::

::: check
kind: parts
given: a = 80 | 100 | 120; b = 40 | 60 | 90

## The 8-bit patterns {a} and {b} (both below 128) are added.

::: part
answer: step(a + b - 128)
tolerance: 0

### What's the overflow flag V?

::: misses
- [any] Two positives giving a result of 128 or more set V.
:::
:::

::: part
answer: a + b - 256*step(a + b - 128)
tolerance: 0

### What's the result read as signed?

::: misses
- [any] Subtract 256 if the top bit is set.
:::
:::
:::

::: check
given: e = 100 | 127 | 150
answer: 2^(e - 127 - 23)
tolerance: 0.001%

## What's the spacing between neighboring single-precision floats with biased exponent {e}?

::: right
Right. $2^{e - 127 - 23}$ = {answer}.
:::

::: misses
- [2^(e - 127)] Divide by the $2^{23}$ steps of the fraction.
- [any] One step of the 23-bit fraction at that exponent.
:::
:::

::: explain
## Why do signal-processing processors saturate instead of wrapping on overflow?

::: model
When a fixed-point result exceeds the largest representable value, wrapping keeps only the low bits, which turns a large positive number into a large negative one: the sign flips and the error is nearly the whole range. In an audio or control signal that's a loud click or a violent jump. Saturating clamps the result to the largest value of the right sign, so the error is only the part that didn't fit, and the signal is clipped rather than inverted. A small error of the right sign is almost always better than a huge error of the wrong one.
:::
:::

::: practice

::: check
given: e = 100 | 110 | 120 | 127 | 130 | 140 | 150
answer: 2^(e - 127 - 23)
tolerance: 0.001%

## Float spacing at biased exponent {e}?

::: misses
- [any] $2^{e - 150}$.
:::
:::
:::
