Sub topic 2
Fixed-point representation
This chapter assumes you know decimal and binary place value, basic binary addition, and powers of two.
Fixed-point representation
A fixed-point number is an integer with an implied binary point at a fixed position. If a value has f fractional bits, the stored integer N represents N / 2^f. The hardware handles only integers, and the scaling is applied by convention.
For example, with f = 4, the value 3.125 is stored as 3.125 × 16 = 50, which is 110010 in binary.
FRAC_BITS = 4
SCALE = 1 << FRAC_BITS # 16
def to_fixed(x):
return round(x * SCALE)
def from_fixed(n):
return n / SCALE
n = to_fixed(3.14159)
print(n, format(n, 'b'), from_fixed(n)) # 50 110010 3.125Fixed-point range, resolution and limitations
Resolution is the smallest step between representable values, 2^-f. For an unsigned format with n total bits and f fractional bits:
- Range: 0 to (2^n − 1) / 2^f
- Resolution: 1 / 2^f
Values that are not multiples of 2^-f must be rounded, so 3.14159 becomes 3.125. Values outside the range overflow. A fixed-point format with a fixed number of fraction bits cannot cover very large and very small magnitudes at once.
Normalized binary scientific notation
Any nonzero binary number can be written as 1.xxx × 2^E, where the leading digit is 1. For example, 101.1 (binary) equals 1.011 (binary) × 2^2, which is 5.5. Normalization lets a floating-point format skip storing the leading 1, because it is always present.
Sign, biased exponent and mantissa fields
A floating-point number has three fields:
- Sign: 1 bit, where 0 is positive and 1 is negative.
- Exponent: stored as E + bias, so the stored value is never negative.
- Mantissa (fraction): the bits after the implicit leading 1.
A bias lets exponents compare as unsigned integers, so no separate sign bit is needed for the exponent.
IEEE 754 single and double precision: encoding and decoding
Single precision uses 32 bits: 1 sign, 8 exponent, 23 fraction, bias 127. Double precision uses 64 bits: 1 sign, 11 exponent, 52 fraction, bias 1023.
To encode -6.5, write it as -1.101 (binary) × 2^2. Then:
| Field | Bits | Value |
|---|---|---|
| Sign | 1 | 1 |
| Exponent | 10000001 | 129 (E = 2 + 127) |
| Fraction | 101 followed by 20 zeros | 5242880 |
import struct
bits = struct.unpack('>I', struct.pack('>f', -6.5))[0]
sign = bits >> 31
exp = (bits >> 23) & 0xFF
frac = bits & 0x7FFFFF
print(hex(bits), sign, exp, frac) # 0xc0d00000 1 129 5242880
value = (-1) ** sign * (1 + frac / 2**23) * 2 ** (exp - 127)
print(value) # -6.5Exercise
What is the IEEE 754 single precision bit pattern for 1.0, in hexadecimal?
Show answer
Sign is 0, the stored exponent is 0 + 127 = 127 (01111111), and the fraction is all zeros. The pattern is 0 01111111 followed by 23 zeros, which is 0x3F800000.