Shelves / Foundations of Computing
CS·06
Number Systems & Data Representation
How bits become integers, real numbers and text. Two's complement, IEEE 754, Unicode and UTF-8, byte order, and the bugs that live at each boundary.
Start here: how computers represent numbers and text
Place value: what "123" really means
You've used base 10 (decimal) all your life without thinking about it. The digits 1, 2, 3 in "123" mean 1 hundred + 2 tens + 3 ones: each position is worth 10 times the position to its right.
| Position value | 100 (10²) | 10 (10¹) | 1 (10⁰) |
|---|---|---|---|
| Digit | 1 | 2 | 3 |
| Contribution | 100 | 20 | 3 |
Nothing is special about ten (it's probably because we have ten fingers). Use any base b: there are b digits (0 to b − 1), and each position is worth b times the one to its right.
Binary: base 2
Computers use base 2 (binary) because their circuits have two reliable states (chapter 1's bits). There are two digits, 0 and 1, and each position is worth twice the one to its right: 1, 2, 4, 8, 16, 32, 64, 128…
Binary to decimal: add up the position values where there's a 1. 101101 = 32 + 8 + 4 + 1 = 45.
| Position value | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|
| Digit | 1 | 0 | 1 | 1 | 0 | 1 |
| Contribution | 32 | 0 | 8 | 4 | 0 | 1 |
Decimal to binary: divide by 2 repeatedly, writing down remainders; read them bottom to top:
13 ÷ 2 = 6 remainder 1
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1
13 in binary (remainders read bottom to top): 1101 | check: 0b1101
(Check: 8 + 4 + 1 = 13.) Languages let you write binary directly with a 0b prefix: 0b1101 is 13.
Adding in binary works like decimal addition, with "carry 1" happening at 2 instead of 10 (1 + 1 = 10 in binary, "zero, carry one"):
0110 (6)
+ 0111 (7)
= 1101 (13)
Hexadecimal: a shorthand for binary
Long binary numbers are hard for people to read, so programmers use base 16 (hexadecimal, "hex"), with digits 0–9 then A–F for ten to fifteen. Its big advantage: one hex digit is exactly four bits, so converting is grouping, not arithmetic:
| Binary | 1111 |
0000 |
0010 |
1111 |
|---|---|---|---|---|
| Hex | F | 0 | 2 | F |
So 0b1111_0000 is 0xF0 (240), and 0x2F = 2 × 16 + 15 = 47. One byte (8 bits) is always exactly two hex digits, from 00 to FF (0 to 255). You'll see hex everywhere: memory addresses (0x7ffd5e8c), colours in web pages (#FF8800 is red 255, green 136, blue 0), file contents, error codes. (Octal, base 8, groups three bits per digit; you'll mostly meet it in Unix file permissions like chmod 755.)
Fixed-size integers, overflow and negative numbers
Inside a computer, an integer has a fixed number of bits: commonly 8, 16, 32 or 64. With n bits you can make 2ⁿ patterns, so:
- An unsigned 8-bit integer holds 0 to 255; 32-bit, 0 to about 4.29 billion; 64-bit, 0 to about 1.8 × 10¹⁹.
- Go past the top and it overflows: like a car's odometer rolling from 999999 to 000000, an 8-bit counter goes 254, 255, 0.
8-bit: 255 + 1 = 0 | -5 in 8-bit two's complement: 11111011 (read as unsigned: 251 )
Negative numbers use a clever scheme called two's complement: the top bit's position counts as negative (in 8 bits, −128 instead of +128). So 11111011 = −128 + 64 + 32 + 16 + 8 + 2 + 1 = −5, and a signed 8-bit integer covers −128 to 127. The reason for this design is that ordinary binary addition then works for negative numbers too, with no special circuits: −5 + 5 gives 00000000 (the carry out of the top bit falls off). The same bits, 11111011, read as unsigned are 251: the bits don't know which they are; the type decides (chapter 2).
Overflow is a real source of bugs and security holes; the full-depth sections show exactly how each language handles it (C and C++ treat signed overflow as undefined; Java and Go wrap; Rust panics in debug builds).
Fractions: why 0.1 + 0.2 isn't 0.3
Positions to the right of the point work the same way: in decimal they're tenths and hundredths; in binary they're halves, quarters, eighths, sixteenths. Some fractions that are simple in decimal can't be written exactly in binary, just as 1/3 = 0.3333… never ends in decimal:
0.1 in binary ≈ 0.000110011001… (the pattern 0011 repeats forever)
0.1 + 0.2 = 0.30000000000000004
A computer keeps only a fixed number of binary digits (about 53 significant bits for a standard 64-bit floating-point number, roughly 15–17 decimal digits), so 0.1 is stored as the closest value it can represent, which is very slightly off. Add two slightly-off numbers and the result is slightly off too. This isn't a bug in your language: it's the format (IEEE 754, explained in depth below). Two practical rules follow immediately:
- Don't compare floating-point numbers with
==; check whether they're close enough (within a small tolerance). - Don't use floating point for money. Store paise or cents as integers, or use a decimal type (chapter 6's lab shows the bugs).
Text: characters are numbers too
Text is stored by giving every character a number (its code point) and storing the numbers:
[('H', 72, '01001000'), ('i', 105, '01101001'), ('!', 33, '00100001')]
- ASCII (1963) numbered 128 characters (English letters, digits, punctuation, control codes) using 7 bits.
Ais 65,ais 97,0is 48, the space is 32. - Unicode numbers every character in every writing system (over 150,000 code points): Hindi, Telugu, Chinese, Arabic, mathematical symbols, emoji.
₹is U+20B9 (U+ followed by the number in hex). - UTF-8 is the standard way to store Unicode as bytes. It uses 1 byte for ASCII characters (so plain English text is unchanged) and 2, 3 or 4 bytes for others:
'A': code point U+0041, UTF-8 bytes 41 (1 byte)
'é': code point U+00E9, UTF-8 bytes c3 a9 (2 bytes)
'₹': code point U+20B9, UTF-8 bytes e2 82 b9 (3 bytes)
'😀': code point U+1F600, UTF-8 bytes f0 9f 98 80 (4 bytes)
Consequence: the number of bytes in a string isn't the number of characters, and the number a language reports as a string's "length" depends on what it counts. When text turns into garbage like é on a web page, bytes were decoded with the wrong encoding (the full-depth sections explain how to prevent it).
Byte order
A number larger than one byte (a 32-bit integer is 4 bytes) must be stored as several bytes in a row, and there are two possible orders: big-endian (most significant byte first, like writing numbers left to right) and little-endian (least significant byte first). Most CPUs today (x86, ARM in its usual mode) are little-endian; network protocols traditionally use big-endian ("network byte order"). It matters whenever bytes cross between systems: files, networks, binary formats.
Check yourself
How deep to go in data representation
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere and L4 in the labs at the end, which is the foundation every later volume builds on.
| Level | What you can do |
|---|---|
| L1 | Convert between bases; know the integer and floating-point formats exist |
| L2 | Pick correct types; handle overflow, rounding and text encoding in code |
| L3 | Explain two's complement, IEEE 754 layout and rounding, UTF-8's design, endianness |
| L4 | Diagnose overflow bugs, precision loss, mojibake, byte-order and serialization mismatches |
| L5 | Choose representations: integers vs decimals for money, timestamps, identifiers, wire formats and their evolution |
| L6 | Keep data correct across systems and years: schema evolution, encoding migrations, cross-language precision |
Positional number systems
Bases and place value
A positional number system with base (radix) b writes a number as digits dₖ…d₁d₀, where each digit is worth dᵢ × bⁱ:
decimal 4 0 7 = 4·10² + 0·10¹ + 7·10⁰ = 407
binary 1 1 0 0 1 0 1 1 1 = 256+128+16+4+2+1 = 407
octal 6 2 7 = 6·64 + 2·8 + 7 = 407
hex 1 9 7 = 1·256 + 9·16 + 7 = 407
Computers use binary (base 2) because a transistor reliably distinguishes two voltage levels: low and high, 0 and 1. A bit is one binary digit. Bits group into larger units:
| Unit | Bits | Notes |
|---|---|---|
| nibble | 4 | one hex digit |
| byte | 8 | the smallest addressable unit on every modern CPU |
| word | 16 / 32 / 64 | the CPU's natural integer size; "word" means 16 bits in x86 assembly naming, 64 on a 64-bit machine in general talk |
| kilobyte | KB = 1000 bytes; KiB = 1024 bytes | storage vendors use powers of 10, RAM and OSes often use powers of 2 |
The KB/KiB difference is why a "1 TB" disk shows up as about 931 GiB.
Hexadecimal and octal
Hexadecimal (base 16, digits 0–9 and A–F) is the human-friendly form of binary. Each hex digit is exactly 4 bits, so conversion is digit-by-digit with no arithmetic:
binary 1101 1110 1010 1101 1011 1110 1110 1111
hex D E A D B E E F → 0xDEADBEEF
You'll see hex in memory addresses (0x7ffd5c2a), colours (#2f43c9 = R 0x2f, G 0x43, B 0xc9), UUIDs, hashes (SHA-256 = 64 hex digits = 256 bits), byte dumps (xxd, hexdump), and Unicode code points (U+1F44D).
Octal (base 8, 3 bits per digit) survives mainly in Unix permissions: chmod 755 means rwx r-x r-x (7 = 111, 5 = 101). It also survives as a trap: in C, C++, Java and JavaScript (non-strict), a leading zero makes a literal octal, so 010 == 8. Go also treats 010 as octal but recommends 0o10. Rust and Zig require 0o10, and 010 is just decimal 10 in Rust.
Literal syntax across languages:
| Binary | Octal | Hex | Digit separator | |
|---|---|---|---|---|
| C (C23) | 0b1010 |
010 |
0xFF |
1'000'000 |
| C++14+ | 0b1010 |
010 |
0xFF |
1'000'000 |
| Java | 0b1010 |
010 |
0xFF |
1_000_000 |
| Rust | 0b1010 |
0o10 |
0xFF |
1_000_000 |
| Zig | 0b1010 |
0o10 |
0xFF |
1_000_000 |
| Go | 0b1010 |
0o10 (or 010) |
0xFF |
1_000_000 |
Converting between bases
- To decimal: sum digit × base^position (above).
- From decimal to base b: repeatedly divide by b and collect the remainders, which come out least-significant first.
407 ÷ 2 = 203 r 1
203 ÷ 2 = 101 r 1
101 ÷ 2 = 50 r 1
50 ÷ 2 = 25 r 0
25 ÷ 2 = 12 r 1
12 ÷ 2 = 6 r 0
6 ÷ 2 = 3 r 0
3 ÷ 2 = 1 r 1
1 ÷ 2 = 0 r 1 read upward: 110010111
- Between binary, octal and hex: group bits in fours (hex) or threes (octal) from the right.
- Fractions: repeatedly multiply by the base and collect integer parts. 0.625 → 1.25 (1) → 0.5 (0) → 1.0 (1), so it's 0.101₂. Many decimal fractions never terminate in binary. 0.1 = 0.0001100110011…₂ repeating, which is the root of every floating-point surprise below.
let n = 407u32;
println!("{n:b} {n:o} {n:x} {n:#X} {n:#010b}"); // 110010111 627 197 0x197 0b110010111
let parsed = u32::from_str_radix("197", 16)?; // 407
let bytes = n.to_be_bytes(); // [0, 0, 1, 151]
n := 407
fmt.Printf("%b %o %x %#X %08b\n", n, n, n, n, n)
v, _ := strconv.ParseInt("197", 16, 64) // 407
s := strconv.FormatInt(407, 36) // "b9": base 36 uses 0-9a-z
int n = 407;
Integer.toBinaryString(n); // "110010111"
Integer.toHexString(n); // "197"
Integer.parseInt("197", 16); // 407
HexFormat.of().formatHex(new byte[]{1, (byte) 0x97}); // "0197" (Java 17+)
printf("%o %x %#X\n", 407, 407, 407); // 627 197 0X197 (C23 adds %b)
long v = strtol("197", NULL, 16); // 407
std.debug.print("{b} {o} {x} {X}\n", .{ 407, 407, 407, 407 });
const v = try std.fmt.parseInt(u32, "197", 16); // 407
Integers
Unsigned integers
An unsigned n-bit integer uses all n bits for magnitude, with range 0 to 2ⁿ − 1:
| Bits | Max value | Common names |
|---|---|---|
| 8 | 255 | uint8_t, u8, byte (Go), unsigned char |
| 16 | 65,535 | uint16_t, u16, char (Java: an unsigned 16-bit UTF-16 unit!) |
| 32 | 4,294,967,295 (~4.3 billion) | uint32_t, u32, uint32 |
| 64 | 18,446,744,073,709,551,615 (~1.8 × 10¹⁹) | uint64_t, u64, uint64 |
Arithmetic is modulo 2ⁿ: 255 + 1 in a u8 wraps to 0, and 0 − 1 wraps to 255. Wrapping is defined for unsigned types in C, C++ and Go. Rust panics in debug builds, and Zig treats it as illegal behaviour in safe builds, unless you ask for wrapping explicitly.
Unsigned arithmetic hides traps:
for (unsigned i = n - 1; i >= 0; i--) { … } // INFINITE LOOP: i >= 0 is always true for unsigned
size_t len = strlen(s);
if (len - 1 > 10) { … } // if len == 0, len - 1 is SIZE_MAX: the branch is taken
The Google C++ style guide's advice to avoid unsigned types for quantities, and Java's choice to have no unsigned types at all, reflect how often this bites. Rust and Zig index with the unsigned usize and catch underflow with checks in debug or safe builds. Go deliberately uses the signed int for lengths and indices to avoid these traps.
Signed integers and two's complement
How do you represent negative numbers in bits? Three schemes have been used:
- Sign-magnitude: one sign bit plus the magnitude. It has two zeros (+0 and −0) and needs different hardware for addition depending on signs. Floats still use this idea.
- Ones' complement: negate by flipping every bit. It also has two zeros, and needs an "end-around carry."
- Two's complement: negate by flipping every bit and adding 1. Every modern CPU uses this, and C23 and C++20 finally require it.
In two's complement, the top bit has negative weight:
8-bit two's complement: value = −128·b₇ + 64·b₆ + 32·b₅ + 16·b₄ + 8·b₃ + 4·b₂ + 2·b₁ + 1·b₀
0111 1111 = 127 (largest)
0000 0001 = 1
0000 0000 = 0 (only one zero)
1111 1111 = −128 + 127 = −1
1000 0000 = −128 (smallest; has no positive counterpart)
negate 5: 0000 0101 → flip → 1111 1010 → +1 → 1111 1011 = −5
Why did two's complement win? Because addition is the same circuit for signed and unsigned values. The adder just adds bit patterns modulo 2ⁿ, and whether you interpret the result as signed or unsigned is up to you. Subtraction is addition of the negation: a − b = a + (~b + 1). The CPU feeds ~b into the adder with carry-in = 1, so there is one adder for everything. The CPU sets flags for both interpretations: the carry flag signals unsigned overflow, and the overflow flag signals signed overflow.
The range of an n-bit signed integer is −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1: −128..127 for 8 bits, about ±2.1 billion for 32, and about ±9.2 × 10¹⁸ for 64. The asymmetry has consequences:
abs(INT_MIN)and-INT_MINoverflow. In Java,Math.abs(Integer.MIN_VALUE)returnsInteger.MIN_VALUE, a negative number.INT_MIN / -1overflows. It's UB in C and traps with SIGFPE on x86.hashCode() % ncan be negative, andMath.abs(hashCode()) % ncan still be negative forMIN_VALUE. UseMath.floorMod(h, n)or(h & 0x7fffffff) % n.
Sign extension and truncation
Widening a signed value to more bits copies the sign bit into the new high bits (sign extension). That keeps the value: 8-bit −5 is 1111 1011, and 16-bit −5 is 1111 1111 1111 1011. Widening an unsigned value fills with zeros (zero extension). Narrowing (truncation) drops high bits, which keeps the value only if it fits.
The classic Java bug: byte is signed (−128..127), so reading bytes as unsigned values needs a mask.
byte b = (byte) 0xF0; // -16
int wrong = b; // -16 (sign-extended to 0xFFFFFFF0)
int right = b & 0xFF; // 240 (mask keeps only the low 8 bits)
int alsoRight = Byte.toUnsignedInt(b);
In C, whether plain char is signed is implementation-defined: signed on x86 Linux, unsigned on ARM Linux. Code like if (c == 0xFF) behaves differently on different platforms. Use unsigned char or uint8_t for bytes.
Integer types across languages
| C / C++ | Java | Rust | Zig | Go | |
|---|---|---|---|---|---|
| Fixed widths | int8_t…int64_t, uint8_t… |
byte 8, short 16, int 32, long 64 (all signed) |
i8…i128, u8…u128 |
i0…i65535, u0…u65535 (any width!) |
int8…int64, uint8…uint64 |
| "Natural" int | int (≥16 bits, 32 in practice), long (32 on Windows, 64 on Linux!) |
— | — | c_int for C interop |
int, uint (64-bit on 64-bit platforms) |
| Pointer/size type | size_t, ptrdiff_t, intptr_t |
int indices (arrays max ~2³¹) |
usize, isize |
usize, isize |
int for len, uintptr |
| 128-bit | __int128 (extension) |
BigInteger |
i128/u128 |
i128/u128 |
math/big, bits.Mul64 |
| Arbitrary precision | GMP | BigInteger |
num-bigint crate |
std.math.big |
math/big |
Zig's arbitrary-width integers are genuinely useful. u3 holds 0..7 exactly, so a packed struct of u3 and u5 is one byte, and @as(u7, x) documents and enforces a range.
Bitwise operations and tricks
With two's complement, a small set of bit tricks becomes standard vocabulary. You'll see them in hash tables, allocators, compression, graphics and interview problems:
| Expression | Effect | Example (x = 0b10110100) |
|---|---|---|
x & (1 << k) |
Test bit k | k = 2 → non-zero |
x \| (1 << k) |
Set bit k | |
x & ~(1 << k) |
Clear bit k | Go: x &^ (1 << k) |
x ^ (1 << k) |
Toggle bit k | |
x & (x − 1) |
Clear the lowest set bit | 0b10110000 |
x & −x |
Isolate the lowest set bit | 0b00000100 (Fenwick trees, chapter 3) |
x & (x − 1) == 0 |
Is x a power of two (or 0)? | used for capacity checks |
(x + 7) & ~7 |
Round up to a multiple of 8 | alignment in allocators |
x >> k / x << k |
Divide or multiply by 2ᵏ | arithmetic >> rounds toward −∞ for negatives (−7 >> 1 = −4) |
popcount(x) |
Count set bits | Hamming distance, bitboards |
clz(x) / ctz(x) |
Count leading or trailing zeros | ⌊log₂ x⌋ = 63 − clz(x) for u64 |
Every language exposes the hardware instructions: Rust x.count_ones(), leading_zeros(), trailing_zeros(), rotate_left(); Go math/bits.OnesCount64, LeadingZeros64; Java Long.bitCount, numberOfLeadingZeros; C++20 <bit>'s std::popcount, std::countl_zero, std::has_single_bit; C23 <stdbit.h>; Zig @popCount, @clz, @ctz.
Floating point
Scientific notation in binary
Integers can't represent 0.5, 6.022 × 10²³ or 1.6 × 10⁻¹⁹. Floating point represents real numbers approximately, the way scientific notation does: a significand (mantissa) times a power of the base.
decimal: 6.022 × 10²³
binary: 1.0110₂ × 2⁵ = 1.375 × 32 = 44
The "point floats" according to the exponent, so you get a huge range, at the cost of a fixed number of significant digits (precision). Before 1985, every vendor had its own format. IEEE 754 standardised it, and now every CPU, GPU and language agrees.
IEEE 754 layout
| Format | Total bits | Sign | Exponent | Fraction | Exponent bias | Decimal digits | Approx. range |
|---|---|---|---|---|---|---|---|
binary16 (half, f16) |
16 | 1 | 5 | 10 | 15 | ~3.3 | ±65,504 |
| bfloat16 (ML) | 16 | 1 | 8 | 7 | 127 | ~2.4 | same as f32 |
binary32 (float, f32) |
32 | 1 | 8 | 23 | 127 | ~7.2 | ±3.4 × 10³⁸ |
binary64 (double, f64) |
64 | 1 | 11 | 52 | 1023 | ~15.9 | ±1.8 × 10³⁰⁸ |
The encoding has some clever details:
- The hidden bit: a normalised binary significand always starts with "1.", so the 1 isn't stored. 23 stored bits give 24 bits of precision.
- Biased exponent: the exponent is stored as an unsigned number plus a bias (127). That makes the whole bit pattern of a positive float sort like an integer. Radix sorts and databases exploit this: flip the sign bit for positives and all bits for negatives, and you get an integer key whose order matches the float order.
- Precision is relative: there are 2²³ representable values between 1 and 2, and also 2²³ between 1024 and 2048. The gap between adjacent floats (one ULP, unit in the last place) grows with magnitude. Above 2²⁴ = 16,777,216,
f32can't represent every integer: 16,777,217 rounds to 16,777,216. Forf64the threshold is 2⁵³ ≈ 9 × 10¹⁵, which is why JavaScript'sNumber.MAX_SAFE_INTEGERis 2⁵³ − 1 and why big JSON integer IDs get corrupted (covered below).
Special values: zero, infinity, NaN and subnormals
The extreme exponent values are reserved:
| Exponent bits | Fraction | Meaning |
|---|---|---|
| all 0 | 0 | ±0. Signed zero: -0.0 == 0.0 is true, but 1/-0.0 = −∞ |
| all 0 | ≠ 0 | Subnormal (denormal): 0.fraction × 2^(1−bias). Gradual underflow toward 0 |
| 1…254 (f32) | any | Normal number |
| all 1 | 0 | ±∞. Result of overflow, or x/0 for x ≠ 0 |
| all 1 | ≠ 0 | NaN (not a number): 0/0, ∞ − ∞, √−1. Quiet NaNs propagate; signalling NaNs trap |
NaN is unequal to everything, including itself. NaN == NaN is false and NaN != NaN is true. Every comparison with NaN is false. Consequences:
x != xis the classic NaN test (useisnan,f64::is_nan,Double.isNaN,math.IsNaN).- Sorting arrays containing NaN with
<violates the strict weak ordering contract (chapter 4). Rust providesf64::total_cmp(IEEE totalOrder), and Java'sDouble.compareputs NaN last and orders −0.0 before 0.0. - NaN keys in hash maps can never be found again. Rust forbids
f64keys, becausef64isn'tEq. max(NaN, 1)gives different answers in different languages and instructions. Check the documentation.
Subnormals fill the gap between the smallest normal number (~1.2 × 10⁻³⁸ for f32) and zero, so that x − y == 0 iff x == y. On many CPUs they're 10–100× slower to compute. Audio and ML code often enables "flush to zero" (FTZ/DAZ) mode to avoid that.
Rounding and floating-point error
Most real numbers aren't representable exactly, so every operation rounds to a nearby float. IEEE 754 requires the basic operations (+, −, ×, ÷, √, and fused multiply-add) to be correctly rounded: the result is the exact answer rounded according to the current mode. The default is round to nearest, ties to even ("banker's rounding"), which avoids systematic upward bias.
The famous example:
0.1 is stored as 0.1000000000000000055511151231257827…
0.2 is stored as 0.2000000000000000111022302462515654…
0.1 + 0.2 = 0.3000000000000000444089209850062616…
0.3 is stored as 0.2999999999999999888977697537484345…
→ 0.1 + 0.2 == 0.3 is FALSE in every language that uses IEEE doubles
This is not a bug in your language. It's what binary floating point does with decimal fractions. The rules that follow:
- Never compare floats with
==after arithmetic. Compare with a tolerance:|a − b| ≤ ε · max(|a|, |b|)(relative) or≤ ε_absnear zero. Machine epsilon (the gap above 1.0) is 2⁻²³ ≈ 1.19 × 10⁻⁷ for f32 and 2⁻⁵² ≈ 2.2 × 10⁻¹⁶ for f64. Choose your tolerance from the problem, not blindly from epsilon. - Operations aren't associative:
(a + b) + c ≠ a + (b + c)in general.(1e20 + −1e20) + 1 = 1, but1e20 + (−1e20 + 1) = 0. So parallel sums give different answers depending on how the work is split, and compilers may not reorder float operations unless you allow it (-ffast-math, which also breaks NaN handling). - Catastrophic cancellation: subtracting nearly equal numbers destroys significant digits. Computing variance as E[x²] − E[x]² is a famous trap. Use Welford's algorithm. The quadratic formula has a stable variant for the same reason.
- Summing many values loses precision. Adding a small value to a large running sum rounds the small one away. Use Kahan (compensated) summation, pairwise summation, or sort by magnitude first.
// Kahan summation: carry the rounding error forward
fn kahan_sum(xs: &[f64]) -> f64 {
let (mut sum, mut c) = (0.0f64, 0.0f64);
for &x in xs {
let y = x - c; // subtract the error from last time
let t = sum + y; // big + small: low bits of y are lost…
c = (t - sum) - y; // …recover them (algebraically 0, numerically the lost part)
sum = t;
}
sum
}
fn approx_eq(a: f64, b: f64, rel: f64, abs: f64) -> bool {
(a - b).abs() <= abs.max(rel * a.abs().max(b.abs()))
}
// 0.1 + 0.2 == 0.3 → false; approx_eq(0.1 + 0.2, 0.3, 1e-12, 1e-15) → true
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(0.1f + 0.2f); // 0.3: in float precision the sum rounds to exactly 0.3f
System.out.println(new BigDecimal(0.1)); // 0.1000000000000000055511151231257827021181583404541015625
System.out.println(new BigDecimal("0.1")); // 0.1 exactly: construct from the STRING
System.out.println(Math.ulp(1.0)); // 2.220446049250313E-16
System.out.println(Double.compare(Double.NaN, 1.0)); // 1: NaN sorts last
fmt.Println(0.1 + 0.2) // 0.30000000000000004? No — prints 0.3!
// Go evaluates CONSTANT expressions with arbitrary precision at compile time.
a, b := 0.1, 0.2
fmt.Println(a + b) // 0.30000000000000004: runtime float64 arithmetic
fmt.Println(math.Nextafter(1, 2) - 1) // 2.220446049250313e-16 (machine epsilon)
#include <float.h>
#include <math.h>
#include <stdio.h>
int main(void) {
printf("%.17g\n", 0.1 + 0.2); // 0.30000000000000004
printf("%g\n", DBL_EPSILON); // 2.22045e-16
double z = 0.0;
printf("%g %g %d\n", 1.0 / z, -1.0 / z, isnan(z / z) != 0); // inf -inf 1
return 0;
}
Precision versus range
These two are easy to confuse:
- Range is how large or small a magnitude you can represent. It's set by the exponent bits. f32 reaches 3.4 × 10³⁸.
- Precision is how many significant digits you get at any magnitude. It's set by the fraction bits. f32 gives about 7 decimal digits.
So f32 can represent 10³⁰, but not 10³⁰ + 1 (they're the same float). A 32-bit integer has a much smaller range but exact precision within it. ML training uses bfloat16 because it keeps f32's range (8 exponent bits) and sacrifices precision: gradients span many orders of magnitude but tolerate noise. Chapter 165 of the roadmap covers quantisation (FP8, INT8, INT4), which pushes this trade-off further.
A practical guide to float types:
| Use | Type |
|---|---|
| General numeric code, statistics, coordinates | f64 / double (the default in Java, Go, Rust literals, JSON) |
| Graphics, GPU, large arrays where memory bandwidth matters | f32 |
| ML weights and activations | bf16, fp16, fp8, int8 |
| Money, invoices, anything legally exact | never binary floats: use integers of the minor unit or decimal types |
Money, decimals and fixed point
$0.10 can't be stored exactly in binary, so summing a million dime transactions in double drifts by fractions of a cent. Auditors notice. The options:
- Integers of the smallest unit: store 1999 (cents, paise or satoshis) instead of 19.99. It's fast and exact. You need to know each currency's minor-unit digits (JPY has 0, BHD has 3), and you must decide how to round when dividing (splitting $10 three ways).
- Decimal types: base-10 floating point with arbitrary or large precision. Java
BigDecimal(you must choose aRoundingMode, and compare withcompareTo, notequals, because2.0and2.00have different scales and aren'tequals), C#decimal, Pythondecimal, Goshopspring/decimal(third party) ormath/big.Rat, Rustrust_decimal, and SQLNUMERIC(19,4). - Fixed point: an integer with an implied binary or decimal point. Q16.16 means 16 integer bits and 16 fraction bits, so the value is the integer divided by 65536. It's common in embedded DSPs without FPUs, in deterministic game physics (lockstep networking needs bit-identical results on every machine), and in audio. Multiplying needs a shift: (a × b) >> 16 with a wider intermediate.
BigDecimal price = new BigDecimal("19.99");
BigDecimal qty = BigDecimal.valueOf(3);
BigDecimal total = price.multiply(qty); // 59.97 exactly
BigDecimal perPerson = total.divide(BigDecimal.valueOf(7), 2, RoundingMode.HALF_EVEN); // 8.57
// new BigDecimal("2.0").equals(new BigDecimal("2.00")) → false (scale differs)
// new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) → 0
Characters and text encoding
From characters to numbers: ASCII and code pages
Text is stored by assigning each character a number (a code) and storing the numbers. ASCII (1963) assigns 128 codes using 7 bits: control characters 0–31 (\n = 10, \t = 9, \r = 13), space = 32, digits '0'–'9' = 48–57, 'A'–'Z' = 65–90 and 'a'–'z' = 97–122. Two tricks fall out of the layout. c − '0' converts a digit character to its value. Upper and lower case differ by exactly one bit (0x20), so c | 0x20 lowercases an ASCII letter.
ASCII has no é, ü, ñ, Hindi, Telugu, Chinese, or emoji. The 1980s and 1990s filled the top bit (codes 128–255) with dozens of incompatible code pages: Latin-1 (ISO-8859-1), Windows-1252, KOI8-R, Shift-JIS, and many more. The same byte meant different characters depending on the assumed code page, which produced mojibake ("café" instead of "café"). Mojibake still appears whenever one program writes UTF-8 and another reads it as Latin-1.
Unicode: code points, planes and grapheme clusters
Unicode assigns one number, a code point written U+XXXX, to every character of every writing system: over 150,000 assigned characters across 160+ scripts, plus symbols and emoji. The code space runs from U+0000 to U+10FFFF, divided into 17 planes of 65,536 code points each:
- Plane 0, the Basic Multilingual Plane (BMP), U+0000–U+FFFF: most modern scripts, including Latin, Cyrillic, Greek, Devanagari, Telugu (U+0C00–U+0C7F), CJK ideographs and common symbols.
- Plane 1 and up, the supplementary planes: emoji (😀 is U+1F600), historic scripts, rarer CJK characters, and mathematical alphanumerics.
Unicode separates what a character is from how it's stored. Storage is the job of an encoding (UTF-8, UTF-16, UTF-32).
A user-perceived "character" isn't the same as a code point:
- Combining characters: "é" can be one code point (U+00E9, precomposed) or two (U+0065 'e' + U+0301 combining acute accent). They look identical but compare unequal byte for byte. Normalisation fixes this. NFC composes (prefer it for storage and comparison), and NFD decomposes. macOS file systems historically stored names in NFD, which caused "file not found" bugs when the same name arrived in NFC.
- Grapheme clusters: what a user sees as one character can be many code points. 👍🏽 is thumbs-up + a skin-tone modifier (2 code points). 👨👩👧 is three people joined by zero-width joiners (5 code points). Flags are pairs of regional-indicator letters (🇮🇳 = U+1F1EE U+1F1F3). Devanagari and Telugu syllables combine consonants, virama and vowel signs: "క్ష" is 3 code points forming one cluster.
So "length of a string" has at least four answers:
"👍🏽" UTF-8 bytes: 8 UTF-16 units: 4 code points: 2 grapheme clusters: 1
"é" (NFC) 2 1 1 1
"é" (NFD) 3 2 2 1
Use grapheme clusters for cursor movement, truncating text for display ("…"), and counting characters a user typed. Use bytes for storage limits and buffers. Code points are rarely what you actually want. Grapheme segmentation needs Unicode data tables: Java BreakIterator, Rust's unicode-segmentation crate, Go's rivo/uniseg, ICU in C and C++.
UTF-8
UTF-8 (Ken Thompson and Rob Pike, 1992, designed on a placemat) is a variable-width encoding using 1 to 4 bytes per code point. It's the encoding of about 98% of the web, of Linux, of Go and Rust source and strings, of JSON (required by RFC 8259), of HTML5 by default, and of modern Java's default charset (since JDK 18).
| Code point range | Bytes | Bit pattern | Payload bits |
|---|---|---|---|
| U+0000–U+007F | 1 | 0xxxxxxx |
7 |
| U+0080–U+07FF | 2 | 110xxxxx 10xxxxxx |
11 |
| U+0800–U+FFFF | 3 | 1110xxxx 10xxxxxx 10xxxxxx |
16 |
| U+10000–U+10FFFF | 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
21 |
Worked example: encode 'é' (U+00E9 = 0000 0000 1110 1001).
U+00E9 is in the 2-byte range → 110xxxxx 10xxxxxx with 11 payload bits
payload: 000 1110 1001 → split 00011 | 101001
bytes: 110 00011 = 0xC3 10 101001 = 0xA9 → "é" = C3 A9
That explains the mojibake. Read C3 A9 as Latin-1 and you get "Ã" (0xC3) and "©" (0xA9).
UTF-8's design properties are why it won:
- ASCII compatible: every ASCII file is already valid UTF-8, and bytes below 0x80 always mean ASCII. C string functions,
/path separators and protocol parsers keep working. - Self-synchronising: lead bytes (
0xxxxxxx,11xxxxxx) and continuation bytes (10xxxxxx) are distinguishable. From any byte offset you can find the start of the next character, and corruption affects only one character. - No byte-order issues: it's a byte sequence, so there's no endianness and no BOM needed.
- Sort order is preserved: byte-wise comparison of UTF-8 strings gives code-point order.
- Compact for Latin-script text. For CJK it uses 3 bytes per character versus UTF-16's 2. Telugu and Devanagari are also 3 bytes per code point in UTF-8.
Invalid UTF-8 exists: overlong encodings (encoding '/' as C0 AF to sneak past security filters was a real attack), lone continuation bytes, surrogate code points, and values above U+10FFFF. Decoders must reject or replace these. Replacement uses U+FFFD, shown as �. Rust's String::from_utf8 returns an error, and from_utf8_lossy substitutes �. Go strings may hold invalid UTF-8, and range yields U+FFFD for bad bytes.
// Encoding and decoding by hand, and with the standard library
r := 'é'
buf := make([]byte, 4)
n := utf8.EncodeRune(buf, r) // n = 2, buf[:2] = C3 A9
fmt.Printf("% X\n", buf[:n]) // C3 A9
dec, size := utf8.DecodeRune(buf[:n]) // 'é', 2
fmt.Println(utf8.ValidString("\xc0\xaf"), dec, size) // false é 2
UTF-16, UTF-32 and the BOM
UTF-16 uses one 16-bit unit for BMP code points and a surrogate pair (two units) for everything above U+FFFF. A code point above the BMP is mapped to a 20-bit value split into a high surrogate (U+D800–U+DBFF) and a low surrogate (U+DC00–U+DFFF). Those code points are reserved, so surrogates never appear as standalone characters.
😀 U+1F600 − 0x10000 = 0x0F600 = 0000 1111 0110 0000 0000 (20 bits)
high = 0xD800 + 0000111101 (0x3D) = 0xD83D low = 0xDC00 + 1000000000 (0x200) = 0xDE00
→ "😀" in UTF-16 = D83D DE00
UTF-16 is the internal string representation of Java (char is a UTF-16 unit), JavaScript, C#/.NET, Windows APIs (wchar_t on Windows), Qt and ICU. It dates from 1990s Unicode, which promised that 16 bits would be enough for everything. When Unicode grew past 65,536 code points, these platforms were stuck with surrogates. Consequences in Java:
String s = "😀a";
s.length(); // 3 — two units for the emoji, one for 'a'
s.charAt(0); // '\uD83D', half a character
s.codePointAt(0); // 128512 (0x1F600)
s.codePoints().count(); // 2
new StringBuilder(s).reverse(); // reverse() is surrogate-aware (keeps pairs together)
s.substring(0, 1); // a lone high surrogate: invalid text if written out as UTF-8
UTF-32 uses 4 bytes per code point, always. It's fixed-width and easy to index, but wasteful, and still not one unit per grapheme. It's mostly used internally (Python's str uses Latin-1, UCS-2 or UCS-4 per string, and C++ has char32_t).
The byte order mark (BOM) is U+FEFF at the start of a file. In UTF-16 and UTF-32 it tells readers the byte order (FE FF is big-endian, FF FE is little-endian). In UTF-8 it's pointless (EF BB BF) but Windows tools sometimes add it, and it then breaks shebang lines, CSV headers and JSON parsers. Strip it on input.
Text in the six languages
| String type | Unit of len |
Indexing | Iterate code points | |
|---|---|---|---|---|
| C | char* (bytes, encoding unknown) |
bytes | bytes | manual decoding, or mbrtowc |
| C++ | std::string (bytes), std::u8string, std::u16string |
bytes / units | bytes / units | no standard decoder (C++20 char8_t helps little); use ICU or a library |
| Java | String (UTF-16 API) |
UTF-16 units | charAt (unit) |
codePoints() |
| Rust | String/&str (valid UTF-8) |
bytes | byte ranges only, on char boundaries | .chars(); graphemes via a crate |
| Zig | []const u8 |
bytes | bytes | std.unicode.Utf8View |
| Go | string (bytes, usually UTF-8) |
bytes | bytes | for _, r := range s (runes) |
Common text bugs
- Truncating mid-character: cutting a UTF-8 byte string at byte 255 can split a multi-byte character and produce invalid UTF-8. Truncate on code-point (or grapheme) boundaries. Database
VARCHAR(255)limits may count bytes or characters depending on the engine. MySQL's legacyutf8charset is actually a 3-byte subset (utf8mb3) that can't store emoji. Useutf8mb4. - Case conversion is locale-dependent: in Turkish, uppercase "i" is "İ" (dotted), and lowercase "I" is "ı" (dotless). Java's
"TITLE".toLowerCase()on a Turkish-locale JVM yields "tıtle", which has broken keyword matching and HTTP header handling in real systems. UsetoLowerCase(Locale.ROOT)for identifiers and protocol keywords. German ß uppercases to "SS", so lengths change. For case-insensitive comparison, use case folding, not lowercasing. - Comparing unnormalised strings: "é" (NFC) ≠ "é" (NFD) byte-wise. Normalise usernames and file names, and be careful with security-sensitive identifiers. Lookalike characters, such as Cyrillic "а" versus Latin "a", enable homograph attacks on domain names. Browsers show such domains in punycode (
xn--…). - Assuming one byte or one char per character in
substring,reverseorcharAtloops. - Wrong charset at the boundary: always state encodings explicitly when reading files, HTTP bodies (
Content-Type: text/html; charset=utf-8) and database connections.
Byte order, alignment and binary formats
Endianness
A multi-byte integer must be stored as several bytes in some order. The 32-bit value 0x0A0B0C0D:
address: +0 +1 +2 +3
big-endian: 0A 0B 0C 0D most significant byte first ("as written")
little-endian: 0D 0C 0B 0A least significant byte first
- Little-endian: x86 and x86-64, nearly all ARM configurations in practice (ARM is bi-endian but runs little-endian), RISC-V, WebAssembly. One nice property: the address of a value is also the address of its low byte, so reading a
u64as au8gives the low byte. - Big-endian: network byte order (IP, TCP and UDP headers), many file formats (PNG, JPEG, Java
.classfiles, Java'sDataOutputStream), and older SPARC, PowerPC and z/Architecture machines.
Endianness doesn't matter within one program on one machine. It matters whenever bytes cross a boundary: files, network packets, memory-mapped hardware, or casting a byte buffer to an integer pointer. The rule is to pick an explicit byte order in every binary format and convert at the boundary:
let v: u32 = 0x0A0B0C0D;
let be = v.to_be_bytes(); // [0x0A, 0x0B, 0x0C, 0x0D]
let le = v.to_le_bytes(); // [0x0D, 0x0C, 0x0B, 0x0A]
let back = u32::from_be_bytes(be); // 0x0A0B0C0D on any machine
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, 0x0A0B0C0D) // 0A 0B 0C 0D
v := binary.LittleEndian.Uint32(buf) // 0x0D0C0B0A: reading with the wrong order
_ = v
ByteBuffer bb = ByteBuffer.allocate(4); // big-endian by default (Java's convention)
bb.putInt(0x0A0B0C0D); // 0A 0B 0C 0D
bb.order(ByteOrder.LITTLE_ENDIAN).getInt(0); // 0x0D0C0B0A
#include <arpa/inet.h> // POSIX
#include <stdint.h>
uint32_t host = 0x0A0B0C0D;
uint32_t net = htonl(host); // host-to-network (big-endian); a no-op on big-endian hosts
// Portable without casts: build the integer from bytes with shifts
uint32_t read_be32(const uint8_t *p) {
return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3];
}
var buf: [4]u8 = undefined;
std.mem.writeInt(u32, &buf, 0x0A0B0C0D, .big);
const v = std.mem.readInt(u32, &buf, .little); // 0x0D0C0B0A
Building integers from bytes with shifts (the C read_be32 above) is endian-independent and avoids the alignment and strict-aliasing UB of casting (uint32_t*)bytes in C. Compilers recognise the pattern and emit a single load plus bswap.
Alignment in binary formats
Chapter 2 showed that structs contain padding. Never write a raw in-memory struct to disk or the network (fwrite(&s, sizeof s, 1, f)). Padding bytes are unspecified (and may leak memory contents), layout differs between compilers and architectures, pointer fields are meaningless in another process, and endianness differs. Serialise field by field into a defined format, or use packed and explicitly laid-out types (#[repr(C, packed)], Zig packed struct/extern struct, Go encoding/binary with fixed-size structs) together with explicit byte order.
Variable-length integers
Most integers in real data are small, so fixed 8-byte fields waste space. Varints use as few bytes as needed. LEB128, used by protobuf, WebAssembly and DWARF, stores 7 bits per byte, and the top bit of each byte says "more bytes follow":
300 = 0b1_0010_1100 → low 7 bits 0101100, next 7 bits 0000010
bytes: 1010 1100 (0xAC, continuation set) 0000 0010 (0x02, last) → AC 02
Negative numbers in plain varints take the maximum 10 bytes, because the sign bits are all ones. ZigZag encoding maps signed to unsigned so that small magnitudes stay small: 0→0, −1→1, 1→2, −2→3… using (n << 1) ^ (n >> 63). Protobuf's sint32/sint64 use ZigZag, while int32 doesn't, so negative int32 fields are expensive.
Numbers across systems: JSON and the 2⁵³ problem
JSON has a single number type and doesn't specify precision. JavaScript parses every number as an IEEE double, so integers above 2⁵³ (9,007,199,254,740,992) silently lose precision:
JSON from a Java/Go backend: {"id": 9007199254740993}
JavaScript after JSON.parse: 9007199254740992 ← a different ID
Twitter famously added id_str fields alongside numeric IDs for this reason. 64-bit Snowflake IDs, database BIGINT keys and nanosecond timestamps are all at risk. Fixes: send large integers as strings in JSON ("id": "9007199254740993"), use a schema that declares int64 (protobuf's JSON mapping does this automatically), or use BigInt on the client. The same caution applies to decimals: send money as strings or as integer minor units.
Serialisation compatibility
Data outlives code, so the bytes you write today will be read by different versions, languages and machines. A compatibility checklist that follows from this chapter:
| Concern | Rule |
|---|---|
| Integer width | Fix the width in the format (int64), never "native int" |
| Signedness | State it, and remember Java has no unsigned types (use the next wider type, or Integer.toUnsignedLong) |
| Byte order | Choose one explicitly (big-endian for network protocols by convention) |
| Floats | IEEE 754 binary64 is universal. Decide how NaN and ±∞ are represented (JSON can't express them) |
| Decimals and money | Strings or scaled integers, never binary floats |
| Text | UTF-8, validated, and normalised (NFC) where identity matters |
| Large integers in JSON | Strings beyond 2⁵³ |
| Time | Use UTC instants as integers (Unix epoch milliseconds or nanoseconds) or RFC 3339 strings with an offset. 32-bit signed Unix time overflows on 19 January 2038 (the Y2038 problem). Use 64-bit |
| Booleans and enums | Use explicit values. Unknown enum values must be tolerated (forward compatibility) |
| Evolution | Add optional fields, never reuse field numbers or tags, never change a field's type in place (chapter 2) |
Binary-to-text encodings
Some channels carry only text: JSON, URLs, email, HTTP headers, configuration files. Base64 encodes every 3 bytes (24 bits) as 4 characters from a 64-symbol alphabet (6 bits each), padding with =, which costs 33% overhead. Base64url replaces +/ with -_ so the output is safe in URLs and file names. JWTs use it. Hex (base16) costs 100% overhead but is readable. Base32 is case-insensitive and avoids ambiguous characters, which is why TOTP secrets use it. Base64 is an encoding, not encryption: anyone can decode it.
"Man" = 4D 61 6E = 010011 010110 000101 101110 → T W F u → "TWFu"
Lab: bits, numbers and text, measured
The bugs in this chapter are silent: no exception, just a wrong number or a garbled name. This lab reproduces the important ones so you recognise them. Everything was run (GCC 13, JDK 21, Rust 1.97, Go 1.24, Zig 0.17, CPython 3.13).
Integer overflow: one operation, five contracts
INT_MAX + 1 in each language:
int x = Integer.MAX_VALUE;
System.out.println("Java MAX+1 = " + (x + 1));
Math.addExact(x, 1); // throws ArithmeticException
let x: i32 = std::hint::black_box(i32::MAX);
println!("{} {:?} {}", x.wrapping_add(1), x.checked_add(1), x.saturating_add(1));
println!("Rust x + 1 = {}", x + 1); // debug build: panics; release build: wraps
x := int32(math.MaxInt32)
fmt.Println("Go MaxInt32+1 =", x+1) // defined: wraps, no error
var x: i32 = std.math.maxInt(i32);
std.debug.print("{d} {d}\n", .{ x +% 1, x +| 1 }); // explicit wrapping and saturating operators
std.debug.print("{d}\n", .{x + 1}); // Debug/ReleaseSafe: panic
Java MAX+1 = -2147483648
Java Math.addExact: integer overflow
Rust wrapping_add: -2147483648 checked_add: None saturating_add: 2147483647
[debug] thread 'main' panicked at ovf.rs:4:34: attempt to add with overflow
[release] Rust x + 1 = -2147483648
Go MaxInt32+1 = -2147483648
Zig +% (wrapping): -2147483648 +| (saturating): 2147483647
Zig thread 4634 panic: integer overflow
| Language | Default on signed overflow | Explicit alternatives |
|---|---|---|
| C, C++ | Undefined behaviour | __builtin_add_overflow, C23 ckd_add, wider types |
| Java | Wraps (defined) | Math.addExact throws; BigInteger |
| Go | Wraps (defined) | math/bits helpers; math/big |
| Rust | Panics in debug, wraps in release (configurable) | checked_, wrapping_, saturating_, overflowing_ methods |
| Zig | Panics in safe modes, UB in ReleaseFast | +% wrap, +| saturate, @addWithOverflow |
Undefined behaviour in action
C's "undefined" isn't "wraps in practice". It lets the compiler assume overflow never happens, and optimise accordingly:
__attribute__((noinline)) int will_overflow(int x) { return x + 1 < x; } // "overflow check" written the wrong way
__attribute__((noinline)) int will_overflow_ok(int x) { return x == INT_MAX; }
$ gcc -O2 -S -o - ub.c # what the "check" compiled to
will_overflow:
endbr64
xorl %eax, %eax # return 0: the comparison was deleted
ret
$ ./ub
x + 1 < x for INT_MAX: 0 ← the check never fires
x == INT_MAX for INT_MAX: 1
__builtin_add_overflow: overflow detected
$ gcc -O2 -fsanitize=undefined -o ubsan ub.c && ./ubsan
ub.c:4:63: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
Mathematically x + 1 < x is false for every integer, and since overflow "can't happen" in a valid program, GCC replaces the function with return 0, even at -O0 here. Overflow checks must be written so they can't overflow themselves (x == INT_MAX, or the compiler builtins). UBSan (-fsanitize=undefined) catches this at run time in tests; enable it (and AddressSanitizer) in CI for C and C++ code. This is also why Rust, Zig and Go define or trap overflow rather than leaving it undefined.
Floating point, measured
print("0.1 + 0.2 =", 0.1 + 0.2, "| == 0.3?", 0.1 + 0.2 == 0.3, "| isclose?", math.isclose(0.1 + 0.2, 0.3))
print("0.1 is stored as exactly", Decimal(0.1))
print("as a fraction:", Fraction(0.1))
f32 = lambda x: struct.unpack("f", struct.pack("f", x))[0]
print("float32(16777217) =", f32(16777217.0))
0.1 + 0.2 = 0.30000000000000004 | == 0.3? False | isclose? True
0.1 is stored as exactly 0.1000000000000000055511151231257827021181583404541015625
as a fraction: 3602879701896397/36028797018963968 = 3602879701896397 / 2^55
float32(16777216) = 16777216.0 float32(16777217) = 16777216.0 ← 2^24 + 1 isn't representable
The double nearest to 0.1 is a fraction with a power-of-two denominator, slightly above 0.1; 0.2 and 0.3 have their own tiny errors, and the errors don't cancel. Compare floats with a tolerance (math.isclose, relative and absolute), never with ==, except for values you know are exact (small integers, results of exact operations).
Precision runs out at the top of the range. A float32 has 24 bits of significand, so above 2²⁴ = 16,777,216 not every integer exists. A float32 counter incremented 20 million times stops:
float32 counter after 20,000,000 increments: 16777216.0
At 16,777,216 the spacing between representable float32 values is 2, so s + 1.0 rounds back to s: the counter silently stops. Doubles hit the same wall at 2⁵³ (the JavaScript id bug in chapter 2). Never use floating point for counters, ids or money.
Errors accumulate. Summing 0.1 ten million times:
naive = 0.0
for _ in range(n): naive += 0.1
kahan, c = 0.0, 0.0
for _ in range(n):
y = 0.1 - c; t = kahan + y; c = (t - kahan) - y; kahan = t # compensated (Kahan) summation
sum of 10^7 × 0.1: naive 999999.9998389754 Kahan 1000000.0000000000 math.fsum 1000000.0000000000
Each addition rounds; the errors add up. Kahan summation carries the lost low-order bits in a compensation term c; math.fsum computes the exactly rounded sum. (Python 3.12 made the built-in sum() of floats use compensated summation too, so a plain for loop and sum() can disagree.) In aggregations over millions of values (analytics, ML loss values), the order and method of summation change the answer.
Money. Classic traps:
int(1.15 * 100) paise = 114 | round(2.675, 2) = 2.67 | Decimal('2.675') rounded half-up = 2.68
ten items at 0.10, loop: 0.9999999999999999 | == 1.0? False | built-in sum() (compensated since 3.12): 1.0
1.15 is stored slightly below 1.15, so × 100 gives 114.999…, and truncation to an integer loses a paisa. round(2.675, 2) gives 2.67 because 2.675 is stored as 2.67499999…. Represent money as integer minor units (paise, cents) in a 64-bit integer, or a decimal type (BigDecimal, Python Decimal, PostgreSQL numeric), with an explicit rounding mode chosen by the business (half-up, half-even), applied at defined points.
NaN breaks ordering:
NaN == NaN: False | sorted([3, nan, 1, 2]) = [3, nan, 1, 2] | max(nan, 1) = nan max(1, nan) = 1
Every comparison with NaN is false, so a sort that relies on < can leave the list unsorted (above, it returned the input unchanged), and max depends on argument order. One NaN from a division by zero in a data pipeline can silently corrupt sorting, aggregation and ML training. Validate (math.isnan) at the boundary; languages offer total orders for floats when you need them (Java's Double.compare, Rust's f64::total_cmp).
Text: one string, five lengths
s = "naïve 🍛 नमस्ते 👩🏽💻"
UTF-8 bytes: 46
UTF-16 code units: 23 (Java/JavaScript/C# String.length())
code points: 19 (Python len, Rust .chars().count(), Go utf8.RuneCountInString)
grapheme clusters: 13 (what a user calls characters)
- Bytes (46): what storage, network limits and
VARCHARbyte limits count. ASCII is 1 byte,ï2, Devanagari 3 per code point, emoji 4. - UTF-16 code units (23): what Java's and JavaScript's
length()return; characters outside the Basic Multilingual Plane (emoji) take two (a surrogate pair), sosubstringcan split one in half. - Code points (19): Unicode scalar values.
- Grapheme clusters (13): what a person sees as characters.
नमस्तेis 6 code points but 3–4 visible units (consonant + vowel signs + virama combine); the developer emoji is 5 code points (woman + skin tone + zero-width joiner + laptop) shown as one glyph.
Practical consequences: "max 20 characters" on a form must say which of these it means (usually graphemes for users, bytes for storage); truncating by bytes or code units can cut a character in half:
truncate to 10 bytes then decode: naïve \uFFFD (replacement character)
Normalisation: the same visible text can have different code points.
'café' == 'café': False | after NFC: True | code points: 4 5
é can be one precomposed code point (U+00E9) or e + combining acute (U+0301). They look identical and compare unequal, so a username or search term entered on one device doesn't match the stored one from another. Normalise (usually to NFC) at input boundaries; for identifiers, also apply case folding and consider confusable characters (Cyrillic а vs Latin a) to prevent spoofing.
Mojibake: bytes decoded with the wrong encoding.
mojibake (UTF-8 read as Windows-1252): naïve
ï is the signature of UTF-8 decoded as Latin-1/Windows-1252: each byte of the 2-byte ï became its own character. The rule that prevents it: decode bytes to text once at the input boundary with the declared encoding (UTF-8 everywhere you control), work with text inside, encode once at the output.
Revision sheet: data representation
Key ideas
- All data is bits; the type decides the meaning. The same 8 bits
11111011are 251 unsigned, −5 signed, or a byte of a UTF-8 sequence. - Positional notation in base b; binary for hardware, hex as 4-bit shorthand, octal for Unix permissions.
- Unsigned n-bit integers cover 0 to 2ⁿ − 1; two's complement signed integers cover −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1, and negate by "invert and add 1".
- Overflow behaviour differs: C/C++ unsigned wraps, signed overflow is undefined behaviour; Java and Go wrap; Rust panics in debug and wraps in release unless you choose
checked_,wrapping_orsaturating_operations; Zig traps in safe modes; Python ints never overflow. - Bitwise operations (AND, OR, XOR, NOT, shifts) manipulate flags and masks; arithmetic right shift keeps the sign, logical shift fills with zeros.
- IEEE 754 floating point: sign, exponent, fraction; doubles carry 53 significant bits (about 15–17 decimal digits). Most decimal fractions are inexact; results round at every step; special values ±0, ±∞ and NaN (NaN ≠ NaN).
- Money and exact quantities: integers in the smallest unit or decimal types (
BigDecimal, Pythondecimal). - Text: Unicode assigns code points; UTF-8 encodes them in 1–4 bytes, ASCII-compatible; UTF-16 (Java, JavaScript strings) uses 2 or 4 bytes. "Length" may mean bytes, UTF-16 units, code points or user-perceived characters (grapheme clusters).
- Byte order: little-endian on x86 and usual ARM; big-endian on the network. Alignment: types sit at multiples of their size, so structs gain padding.
Numbers to remember
- int8 −128..127; uint8 0..255; int32 about ±2.15 × 10⁹; int64 about ±9.22 × 10¹⁸.
- Doubles represent every integer exactly up to 2⁵³ = 9,007,199,254,740,992 (JavaScript's
Number.MAX_SAFE_INTEGERis 2⁵³ − 1). - Float32 has about 7 significant decimal digits.
- UTF-8 lengths: U+0000–007F 1 byte, to U+07FF 2, to U+FFFF 3, beyond 4.
Pitfalls
0.1 + 0.2 == 0.3is false; compare with a tolerance.(int)casts truncate toward zero; rounding is a separate operation.- Mixing signed and unsigned in C comparisons:
-1 < 1uis false. - Decoding bytes with the wrong encoding (mojibake like
é); always state the encoding. - Reversing or slicing strings by bytes or UTF-16 units breaks emoji and combining marks.
- Writing raw structs to files or the network: padding and byte order differ between machines.
Glossary
- Bit / byte / word: 1 binary digit / 8 bits / the CPU's natural integer size (64 bits today).
- Sign extension: copying the sign bit when widening a signed integer.
- Mantissa (significand): the fraction digits of a floating-point number.
- Code point: Unicode's number for a character, written U+XXXX.
- Grapheme cluster: what a reader sees as one character, possibly several code points.
- Endianness: the order bytes of a multi-byte value are stored in.