How numbers are stored

Negatives and decimals in binary Β· Part of Complexity and data

Key idea

Practice

6 questions Β· about 3 min

Explained step by step

Sign bit

The most intuitive way to store a signed integer is to use the first bit as the sign, 0 for positive and 1 for negative, and the rest for the value. It's called sign and magnitude. So 2 is 0000 0010 and βˆ’2 is 1000 0010. The problem is that adding those bits directly gives the wrong answer: 1 + (βˆ’2) gives βˆ’3 instead of βˆ’1. And there are 2 zeros: 0000 0000 and 1000 0000, that is +0 and βˆ’0. It's like having 2 different keys for the same door: it causes confusion.

Two's complement

Computers store signed integers in two's complement. For a positive number, it's the same as always. For a negative one, you flip the value's bits (ones' complement) and add 1. So βˆ’1 in 8 bits is 1111 1111. With this, adding positives and negatives works with the usual addition, and there's a single zero. There's also a spare pattern, 1000 0000, which is used for βˆ’128. That's why a byte goes from βˆ’128 to 127.

Every two's complement calculation is an addition, and that's key: adding is the simplest thing to build in a circuit, the easiest to do in parallel and the fastest. Subtracting a βˆ’ b is adding a + (βˆ’b). Multiplying and dividing can be built from repeated additions and subtractions. That's why two's complement simplifies hardware: the same adder circuit works for positives and negatives, with no special subtractor and no cases for +0 and βˆ’0.

FLOAT (floating point)

A 32-bit float, under the IEEE 754 standard, has 3 parts. 1 sign bit. 8 exponent bits, which say what power of 2 to multiply by. 23 fraction bits, which give the number's digits. It's like scientific notation, 1.5 Γ— 10Β³ = 1,500, but in base 2. The exponent is what lets it reach huge numbers, up to about 3.4 Γ— 10³⁸, with the same 4 bytes as an int.

The float gains range at the cost of precision. An int uses its 32 bits for numbers spaced 1 apart: between 1,000 and 1,001 there's nothing, but every integer in range is exact. In a float, the bigger the number, the further apart the values it can write. That's why it can't store every large integer exactly, and some decimals, like 0.1, don't even have an exact binary version: 0.1 + 0.2 gives 0.30000000000000004.

The float's exponent has 2 reserved values. When the exponent is 0, the number is 0 or a subnormal number, which allows writing values even closer to 0 with less precision. When the exponent is 255, all 1s, the number is infinity or NaN, which means "not a number" and appears with impossible calculations like 0 / 0. That way a float can signal something went wrong without stopping the program.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Negatives and decimals in binary