Skip to content

Lesson 3 of 18How software works

How Data Is Stored

Read hex and binary, know why integers overflow and floats drift, and see how text, files, Base64 and hashes are really just bytes.

18 min read0/5 questions

Here are three bug reports from an ordinary week at a software company. A customer's order ID comes back from the API as 1234567890123456789, but the web page shows 1234567890123456800 and the order cannot be found. An invoice total prints as 0.30000000000000004. A customer called José appears in an export as José. None of these is a logic mistake in the usual sense. Each one comes from how numbers and text are stored as bits, and each one is fixed in minutes once you know what is underneath. In How Code Runs you met bits, bytes and binary counting. This lesson builds on that and covers what engineers actually deal with: hex, integer sizes, floats, text encodings, files, Base64 and hashes.

Hex, octal and binary

Binary is how the machine stores numbers, but long rows of 0s and 1s are hard for people to read. So engineers use two shorthands.

Hexadecimal (base 16) uses the digits 0 to 9 and then a to f for 10 to 15. Its magic is that one hex digit is exactly 4 bits, so two hex digits are exactly one byte. The byte 11111111 is ff in hex and 255 in decimal. Reading a byte in hex is like reading it in binary, with a quarter of the characters.

Octal (base 8) uses the digits 0 to 7. One octal digit is exactly 3 bits. You will rarely see it, with one big exception: file permissions such as chmod 755, which you will decode in the next lesson.

Most languages mark the base with a prefix: 0x for hex, 0o for octal (just 0 in older C code and in chmod), and 0b for binary.

Python
print(0xFF, 0o755, 0b1010) # all just numbersprint(hex(255), oct(493), bin(10)) # and back to textprint(int("ff", 16), int("755", 8)) # parse text in a base r, g, b = 0x1E, 0x90, 0xFF # a CSS colour is three bytesprint(f"#{r:02x}{g:02x}{b:02x}", (r, g, b))
Output
Press Run (⌘ Enter) to see what happens.

Once you can read hex, you will see it everywhere:

  • Colours: #1e90ff is three bytes: red 1e, green 90, blue ff.
  • Hashes and IDs: a Git commit like a3f9c2e... is a hash written in hex. So are UUIDs like 550e8400-e29b-41d4-a716-446655440000.
  • Memory addresses: Python prints objects as <object at 0x104f2a3d0>. That is a location in memory.
  • Byte dumps: tools that show you the raw contents of a file print each byte as two hex digits.
Quick check
A SHA-256 hash is 32 bytes long. How many characters does it take to write it in hex?
Need a nudge? A hint rules out a wrong answer.

Integers have a fixed size

In most languages an integer gets a fixed number of bits, usually 8, 16, 32 or 64. A fixed size means a fixed range:

SizeUnsigned rangeSigned range
8-bit0 to 255−128 to 127
16-bit0 to 65,535−32,768 to 32,767
32-bit0 to about 4.29 billionabout −2.15 billion to 2,147,483,647
64-bit0 to about 1.8 × 10^19about ±9.2 × 10^18

Unsigned integers are zero or positive. Signed integers can be negative, and almost every computer stores them with a trick called two's complement: the top bit counts as a large negative number instead of a positive one. In 8 bits, the columns are worth −128, 64, 32, 16, 8, 4, 2, 1. So 01111111 is 127, and 10000000 is −128.

That trick explains overflow. When you add 1 to the largest value, the bits roll over like a car's odometer, and the number jumps to the most negative value:

127 + 1 in a signed 8-bit integer
-1286432168421
12701111111
+ 1
result

127 is every bit on except the top one. It is the biggest signed 8-bit number.

1/4

Python hides all of this, because its integers grow as big as they need to. You can still simulate a fixed-size integer by keeping only the low 8 bits:

Python
def as_signed_8bit(n): n &= 0xFF # keep only the lowest 8 bits return n - 256 if n >= 128 else n print(as_signed_8bit(127))print(as_signed_8bit(127 + 1)) # overflow wraps aroundprint(as_signed_8bit(-1), format(-1 & 0xFF, "08b")) # -1 is all onesprint(2 ** 64) # real Python ints just keep growing
Output
Press Run (⌘ Enter) to see what happens.

Overflow is not just a textbook idea. A database table with a 32-bit INT primary key can only hold about 2.1 billion rows. Busy systems hit that limit, and suddenly every insert fails. The fix is a painful migration to BIGINT (64-bit) on a huge table, which is why many teams use BIGINT for IDs from day one. Times stored as 32-bit seconds since 1970 run out in January 2038, which is why modern systems use 64 bits for timestamps.

JavaScript numbers and big IDs

JavaScript has one main number type: a 64-bit float (more on floats below). It stores whole numbers exactly only up to Number.MAX_SAFE_INTEGER, which is 2^53 − 1, or 9,007,199,254,740,991. Above that, some integers simply cannot be represented, and JavaScript quietly rounds to the nearest one it can store.

Many backends use 64-bit integer IDs, which go far past 2^53. When a browser parses JSON containing such an ID, the number is rounded before your code ever sees it. That is exactly the first bug report above.

JavaScript
console.log(Number.MAX_SAFE_INTEGER);console.log(9007199254740992 === 9007199254740993); // two different numbers? const order = JSON.parse('{"id": 1234567890123456789}');console.log(order.id); // rounded on parse console.log(BigInt("1234567890123456789") + 1n); // BigInt is exact const i32 = new Int32Array(1); // a real 32-bit integeri32[0] = 2147483647;i32[0] += 1;console.log(i32[0]); // wraps, like the grid above
Output
Press Run (⌘ Enter) to see what happens.

The standard fix is on the API side: send large IDs as strings, like "id": "1234567890123456789". Many big public APIs do exactly this. IDs are labels, not quantities, and you never do maths on them, so a string is the right type anyway. When you really need big integer maths in JavaScript, use BigInt.

Predict the outputJavaScript

What does this print?

console.log(2 ** 53 === 2 ** 53 + 1)
Need a nudge? Hints walk you through it.

Floats: why 0.1 + 0.2 is not 0.3

Numbers with fractions are usually stored as floating point, defined by a standard called IEEE 754. Python's float and JavaScript's number are both the 64-bit version, often called a double. Its 64 bits are split into three parts: 1 sign bit, 11 bits for the exponent (roughly, where the point goes), and 52 bits for the digits. That gives about 15 to 17 significant decimal digits.

The digits are binary fractions: halves, quarters, eighths and so on. A number like 0.5 or 0.75 is exact. But 0.1 is one tenth, and a tenth cannot be written as a finite sum of halves, quarters and eighths, just as one third cannot be written as a finite decimal (0.3333...). So the computer stores the closest double it can, which is very slightly more than 0.1. Add two slightly-wrong numbers and the error can show up in the result.

Python
import mathfrom decimal import Decimal print(0.1 + 0.2)print(0.1 + 0.2 == 0.3)print(math.isclose(0.1 + 0.2, 0.3)) # compare with a toleranceprint(f"{0.1:.20f}") # what is really stored total = 0.0for _ in range(10): # ten payments of 0.10 total += 0.1print(total, total == 1.0) print(sum([Decimal("0.1")] * 10)) # exact decimal arithmeticcents = 1999 + 1 # 19.99 + 0.01 as integer centsprint(cents // 100, cents % 100) nan = float("nan")print(nan == nan, math.isnan(nan)) # NaN is not equal to itself
Output
Press Run (⌘ Enter) to see what happens.

Three rules come out of this, and every one of them shows up in code review:

  1. Never compare floats with ==. Check that they are close: math.isclose(a, b) in Python, or Math.abs(a - b) < 1e-9 in JavaScript. Test frameworks have helpers for this, such as pytest.approx.
  2. Never store money in floats. Store whole cents (or the smallest unit of the currency) as integers, or use a decimal type: Python's Decimal, or NUMERIC in a SQL database. Errors of a fraction of a cent add up across millions of transactions, and accountants notice.
  3. NaN ("not a number") is not equal to anything, even itself. You get it from things like 0/0 in JavaScript or float("nan"). Check for it with math.isnan() or Number.isNaN().

Text: characters, code points and bytes

A computer cannot store a letter, only numbers. So we need an agreed table that maps characters to numbers, and then a way to turn those numbers into bytes.

ASCII, from the 1960s, maps 128 characters (English letters, digits, punctuation) to the numbers 0 to 127. A is 65. That fits in one byte, but it has no é, no ñ, no Chinese, no Arabic.

Unicode is the modern table. It gives every character in every writing system a number called a code point, written like U+00E9 for é. There is room for over a million code points, and about 150,000 are in use.

Unicode is only the table. An encoding decides how a code point becomes bytes. UTF-8 is the encoding the web runs on. It uses 1 to 4 bytes per code point: plain ASCII characters stay 1 byte (so old ASCII files are already valid UTF-8), accented Latin letters take 2, most other scripts take 3, and rarer characters take 4. If someone asks "what is the difference between Unicode and UTF-8?", that is the answer: Unicode assigns the numbers, UTF-8 stores them as bytes.

Python
import unicodedata for ch in ["A", "é", "€", "𝄞"]: data = ch.encode("utf-8") print(ch, f"U+{ord(ch):04X}", len(data), "bytes:", data.hex(" ")) word = "café"print(len(word), len(word.encode("utf-8"))) # characters vs bytes composed = "é" # é as one code pointdecomposed = "é" # e plus a combining accentprint(composed, decomposed, composed == decomposed, len(decomposed))print(unicodedata.normalize("NFC", decomposed) == composed)
Output
Press Run (⌘ Enter) to see what happens.

This is why "how long is this string?" has more than one answer:

  • Bytes: café is 5 bytes in UTF-8. Database column limits and network sizes care about this.
  • Code points: Python's len("café") is 4.
  • UTF-16 code units: JavaScript strings are stored as UTF-16, where some characters take two units. "𝄞".length is 2 in JavaScript but len("𝄞") is 1 in Python.
  • What a person sees: one visible character can be several code points. é can be typed as one code point or as e plus a combining accent, and the two do not compare equal until you normalise them. Many emoji, such as flags and skin-tone variants, are several code points glued together. A visible character like this is called a grapheme cluster.

So if a form says "maximum 20 characters", someone has to decide which of those four it means.

Mojibake: when bytes are read with the wrong encoding

The third bug report, José, has a name: mojibake (Japanese for "character transformation"). It happens when text is written in one encoding and read in another. The bytes are fine. The reading is wrong.

How José becomes José
App writes: encodes as UTF-8App writesencodes as UTF-8File bytes: 4a 6f 73 c3 a9File bytes4a 6f 73 c3 a9Reader A: decodes UTF-8Reader Adecodes UTF-8Reader B: decodes Latin-1Reader Bdecodes Latin-1saveJoséJosé

The app saves José in UTF-8. J, o, s are one byte each. é (U+00E9) becomes two bytes: c3 a9.

1/4

The lesson for work: always say which encoding you mean. In Python, open text files with open(path, encoding="utf-8"). On the web, send Content-Type: text/html; charset=utf-8. In databases, use a UTF-8 character set (in MySQL that is utf8mb4; the older utf8 cannot store 4-byte characters).

Quick check
A CSV export shows Müller instead of Müller. What most likely happened?
Need a nudge? A hint rules out a wrong answer.

Byte order

When a number takes more than one byte, which byte comes first? Big-endian stores the most significant byte first, the way we write numbers. Little-endian stores the least significant byte first. The number 1 as a 4-byte integer is 00 00 00 01 big-endian and 01 00 00 00 little-endian. Almost every laptop and server CPU today (x86-64 and ARM) is little-endian, while network protocols use big-endian, so it is also called network byte order. You only meet this when you read binary formats or protocols byte by byte. Python's int.to_bytes(4, "big") and the struct module let you choose.

Files are just bytes

Every file on disk is a list of bytes. A text file is bytes that are meant to be decoded as characters, usually UTF-8. A binary file (an image, a PDF, a program) is bytes in some other format. The file name's extension, like .png, is only a hint for people and programs. Rename photo.png to notes.txt and the bytes inside do not change.

Most binary formats begin with a fixed signature called a magic number, so programs can tell what a file really is. PNG files start with 89 50 4e 47 (the second to fourth bytes spell PNG), PDFs start with the text %PDF, and ZIP files (including .docx and .jar) start with PK. You can look at raw bytes with xxd or hexdump, and the file command reads the magic number for you:

printf 'caf\xc3\xa9\n' > word.txtxxd word.txt# 00000000: 6361 66c3 a90a                           caf...file word.txt# word.txt: Unicode text, UTF-8 textcp logo.png notes.txtfile notes.txt# notes.txt: PNG image data, 1 x 1, 8-bit grayscale, non-interlacedhead -c 16 notes.txt | xxd# 00000000: 8950 4e47 0d0a 1a0a 0000 000d 4948 4452  .PNG........IHDR

xxd shows the offset on the left, the bytes in hex in the middle, and the printable characters on the right, with dots for bytes that are not printable. Notice c3 a9 for é and 0a for the newline. xxd comes with macOS and with Vim on Linux; hexdump -C is a common alternative. This matters at work in one serious place: if your app accepts file uploads, never trust the extension or the type the browser claims. Check the actual bytes.

Base64 and hashing: two things people mix up

Both turn data into a string of odd-looking characters, and both are regularly confused with encryption. They are completely different tools.

Base64 is an encoding: a reversible way to write any bytes using only 64 safe text characters (A-Z, a-z, 0-9, +, /, with = as padding). Every 3 bytes become 4 characters, so the result is about 33% larger. It exists because many systems only carry text safely: email attachments, JSON fields, data: URLs that embed an image in CSS, the Authorization: Basic header, and the three parts of a JWT (which use a URL-safe variant). Anyone can decode Base64 instantly. It hides nothing.

A hash function, like SHA-256, turns any input into a fixed-size fingerprint (32 bytes, 64 hex characters). The same input always gives the same hash. Change one character and the hash changes completely. And it is one-way: there is no "unhash". Hashes are used to check that a download was not corrupted, to name things by their content (Git names every commit and file by a hash of its contents), and as cache keys.

Encryption is the third, different thing: it scrambles data with a key, and only someone with the right key can reverse it. HTTPS is encryption.

echo -n 'hello' | base64# aGVsbG8=echo 'aGVsbG8=' | base64 -d# helloecho -n 'hello' | shasum -a 256      # macOS# 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824  -echo -n 'hello' | sha256sum          # Linux (recent macOS has it too)shasum -a 256 installer.dmg          # compare with the checksum on the download page

echo -n stops echo adding a newline, which would change the bytes and so the hash. Older macOS versions spell the decode flag -D; current ones accept -d.

Match the pairs0/5 matched

Match each job to the right tool.

Choose an item, then its match on the other side.
Put it in order4 steps

Order these by how many bytes they take in UTF-8, fewest first.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
hexadecimal
Base 16, digits 0-9 and a-f. One hex digit is 4 bits, so two hex digits are one byte.
two's complement
The standard way to store signed integers: the top bit counts as a large negative value.
overflow
When a fixed-size integer goes past its maximum and wraps around, or a value no longer fits its type.
floating point
IEEE 754 numbers stored as binary fractions with an exponent. Fast, but most decimals are approximate.
code point
The number Unicode assigns to a character, written like U+00E9.
UTF-8
The dominant text encoding. Stores each code point in 1 to 4 bytes and is compatible with ASCII.
Base64 vs hash
Base64 is a reversible encoding to safe text. A hash is a one-way, fixed-size fingerprint. Neither is encryption.