A lesson from the Computer Memory module of the bootcamp. About a 13 minute read.
Negative numbers and fractions do not exist in hardware. They are agreements about how to read bit patterns, and there are exactly two you need: two's complement for integers and IEEE 754 for fractions. Between them they explain integer overflow, why the most negative number has no positive twin, and why 0.1 + 0.2 is not 0.3 in every language you will ever use.
In TWO'S COMPLEMENT an n-bit pattern is read exactly like an unsigned number with one change: the top bit's weight is negative, -2^(n-1) instead of +2^(n-1). In a byte, 01111111 is 127, 10000000 is -128, and 11111111 is -128 + 127 = -1. To negate any number, flip every bit and add one, and it is worth checking once by hand on 5: 00000101 flips to 11111010, add one to get 11111011, which is -128 + 64 + 32 + 16 + 8 + 2 + 1 = -5. That is the whole encoding. Every integer type in every mainstream language works this way, and since C++20 even the C++ standard, which spent decades carefully not promising it, requires it.
The rest of this lesson continues with 7 further sections. See the full curriculum.
Browse all 546 practice puzzles