← Back to Home

🔢 How Computers Represent Numbers and Text

Integer overflow, floating point, money, JavaScript's 2⁵³ limit, UTF-8, mojibake and what a 'character' really is.

0.1 + 0.2 isn't 0.3. A YouTube view counter broke in 2014. An "é" can be one character or two. A rocket exploded because a number didn't fit. These all trace back to one fact: a computer stores everything as fixed-size patterns of bits, and the choice of how to map numbers and text onto those bits has consequences.

This article covers integers, floating point and text encodings, and the bugs each one causes in real software.

Binary and hexadecimal

Computers store numbers in binary (base 2). Each bit is a power of two, so 101010 is 32 + 8 + 2 = 42. Binary gets long quickly, so we usually write it in hexadecimal (base 16), where each hex digit is exactly 4 bits and a byte is exactly two hex digits.

print(bin(42), hex(255), int("ff", 16), 0b101010)
# 0b101010 0xff 255 42

Hex is everywhere: memory addresses (0x7ffd5e8c), colors (#667eea), hashes (sha256: 9f86d0…), MAC addresses, and Unicode code points (U+20AC).

Integers and two's complement

A fixed-size integer has a fixed range:

Type Bits Range
uint8 8 0 to 255
int16 16 −32,768 to 32,767
int32 32 −2,147,483,648 to 2,147,483,647
int64 64 about ±9.2 × 10¹⁸

Negative numbers use two's complement: to negate a number, invert all its bits and add 1. In 8 bits, 5 is 00000101 and −5 is 11111011. The nice property is that the same adder circuit works for both signed and unsigned numbers. The top bit acts as the sign.

print(format(-5 & 0xFF, "08b"), -5 & 0xFF)   # 11111011 251  (same bits, read as unsigned)

Overflow

When a result doesn't fit, fixed-size integers wrap around:

import ctypes

print(ctypes.c_int32(2**31 - 1).value)   # 2147483647, the largest int32
print(ctypes.c_int32(2**31).value)       # -2147483648, one more wraps to the most negative value

Python's own int grows as needed, so it never overflows, but C, C++, Java, Go, Rust (in release builds), and the database columns and file formats you talk to all use fixed sizes. Real incidents:

Floating point

How do you store 3.14159 or 6.02 × 10²³ in 64 bits? IEEE 754 floating point uses scientific notation in binary:

value = sign × 1.mantissa × 2^exponent

64-bit double: 1 sign bit | 11 exponent bits | 52 mantissa bits

That gives an enormous range (about 10⁻³⁰⁸ to 10³⁰⁸) but only about 15–17 significant decimal digits of precision. A 32-bit float has about 7.

Why 0.1 + 0.2 ≠ 0.3

Just as 1/3 has no exact decimal representation (0.3333…), 0.1 has no exact binary representation. It's a repeating binary fraction, so it gets rounded to the nearest representable double:

from decimal import Decimal

print(0.1 + 0.2)              # 0.30000000000000004
print(0.1 + 0.2 == 0.3)       # False
print(Decimal(0.1))           # 0.1000000000000000055511151231257827021181583404541015625

Every language that uses IEEE 754 doubles behaves this way. That includes JavaScript, Java, C, Go and Python. It's not a Python bug.

Small rounding errors also accumulate:

total = 0.0
for _ in range(10):
    total += 0.1
print(total)                  # 0.9999999999999999

print(sum([0.1] * 10))        # 1.0 on Python 3.12+, which uses compensated summation in sum()
import math
print(math.fsum([0.1] * 10))  # 1.0, exactly rounded summation on any version

The Patriot missile failure in 1991 came from the same effect. The system counted time in tenths of a second, using a 24-bit binary approximation of 0.1. After 100 hours of uptime, the accumulated error was about a third of a second, enough to miss an incoming missile. 28 soldiers died.

Rules for working with floats

1. Never compare floats with ==. Compare with a tolerance:

import math
print(math.isclose(0.1 + 0.2, 0.3))     # True

2. Never store money in floats. Use integer minor units (cents) or a decimal type:

from decimal import Decimal

print(Decimal("0.1") + Decimal("0.2"))  # 0.3, exact decimal arithmetic
price_cents = 1999                      # €19.99 stored as an integer
print(f"€{price_cents * 3 / 100:.2f}")  # €59.97, convert only for display

In databases, use NUMERIC/DECIMAL columns for money, not FLOAT/DOUBLE.

3. Know your rounding mode. Python's round() uses "banker's rounding" (round half to even): round(2.5) is 2 and round(3.5) is 4. Separately, round(2.675, 2) gives 2.67, not 2.68, because the double closest to 2.675 is actually 2.67499999999999982…. For financial rounding, use Decimal.quantize with an explicit rounding mode.

4. Large integers lose precision as floats. A double holds every integer exactly only up to 2⁵³ (9,007,199,254,740,992). Above that, gaps appear.

JavaScript and 2⁵³

JavaScript's Number is always a 64-bit double, which catches people out with large IDs:

console.log(9007199254740993);          // 9007199254740992 (the last digit silently changed)
console.log(Number.MAX_SAFE_INTEGER);   // 9007199254740991
console.log(9007199254740993n + 1n);    // 9007199254740994n (BigInt is exact)

That's why Twitter's API returns tweet IDs as both a number and a string (id_str), and why you should serialize 64-bit IDs as strings in JSON.

Special values

IEEE 754 also defines +Infinity, −Infinity, −0.0, and NaN ("not a number", from 0/0 or sqrt(-1)). NaN is the only value not equal to itself (nan != nan), which can quietly break sorting and de-duplication if NaNs get into your data.

Byte order (endianness)

Multi-byte numbers can be stored with the most significant byte first (big-endian) or last (little-endian):

print((1).to_bytes(4, "big"))      # b'\x00\x00\x00\x01'
print((1).to_bytes(4, "little"))   # b'\x01\x00\x00\x00'

x86 and most ARM systems are little-endian. Network protocols (TCP/IP headers) use big-endian, also called network byte order. It matters whenever you parse binary formats or packets by hand. Use struct with an explicit < or >, or int.from_bytes, never assume.

Text: characters are not bytes

From ASCII to Unicode

ASCII (1963) mapped 128 characters (English letters, digits, punctuation, control codes) onto 7 bits. That works for English and nothing else. Dozens of incompatible 8-bit "code pages" followed, and text moved between them turned into garbage.

Unicode fixed this by giving every character in every writing system a unique number called a code point, written U+XXXX. There's room for over a million code points, and nearly 160,000 are currently assigned. A is U+0041, é is U+00E9, € is U+20AC, 👍 is U+1F44D.

Unicode itself is only the numbering. An encoding decides how code points become bytes.

UTF-8

UTF-8 encodes each code point in 1 to 4 bytes:

for ch in ["A", "é", "€", "👍"]:
    print(repr(ch), hex(ord(ch)), ch.encode("utf-8"), len(ch.encode("utf-8")), "bytes")
# 'A'  0x41    b'A'                  1 bytes
# 'é'  0xe9    b'\xc3\xa9'           2 bytes
# '€'  0x20ac  b'\xe2\x82\xac'       3 bytes
# '👍' 0x1f44d b'\xf0\x9f\x91\x8d'   4 bytes

UTF-8's key strengths are that ASCII text is already valid UTF-8, byte for byte, and that it never produces a zero byte except for the actual NUL character, so old C string handling mostly keeps working. It's used by about 98% of websites. Default to UTF-8 everywhere: files, databases, APIs, source code.

One trap: MySQL's utf8 character set is a 3-byte subset that can't store emoji. Use utf8mb4.

Mojibake

When bytes written in one encoding are read as another, you get mojibake:

print("café".encode("utf-8").decode("latin-1"))   # café

If you see é, ’ or  in your data, UTF-8 bytes were decoded as Latin-1 or Windows-1252 somewhere along the way. The fix is to make every boundary (file reads, HTTP headers, database connections) state its encoding explicitly.

What is a "character", anyway?

There are at least three answers, and they give different lengths:

Unit Meaning len("👨‍👩‍👧")
Bytes (UTF-8) Storage size 18
UTF-16 code units What JavaScript's and Java's .length count 8
Code points What Python's len() counts 5
Grapheme clusters What a human sees as one character 1

The family emoji is three person emoji joined by two invisible "zero-width joiner" code points. Skin tones work the same way: "👍🏽" is a thumbs-up plus a modifier, so len("👍🏽") is 2 in Python.

console.log("👍".length);        // 2: JavaScript counts UTF-16 code units
console.log([..."👍"].length);   // 1: spreading iterates by code point

So a "max 280 characters" check, or truncating a username to 20 characters, can cut an emoji in half or count wrong. For user-facing lengths and truncation, count grapheme clusters: Intl.Segmenter in JavaScript, the regex module's \X or the grapheme package in Python.

Normalization

The same visible text can be encoded in different ways. é can be one code point (U+00E9) or e followed by a combining accent (U+0065 U+0301):

import unicodedata

a = "café"          # é as one code point
b = "café"         # e + combining acute accent
print(a, b, a == b, len(a), len(b))                 # café café False 4 5
print(unicodedata.normalize("NFC", b) == a)         # True

Two usernames that look identical can compare as different, and two different ones can look the same. Normalize text (usually to NFC) before comparing, hashing or storing identifiers. Lookalike characters from different alphabets, such as Latin a and Cyrillic а, are also behind homograph phishing domains.

Cheat sheet

Situation Do this
Counting things, IDs Integers; use 64-bit for anything that might grow
Money Integer cents or Decimal / SQL NUMERIC, never float
Measurements, science, graphics Floats are fine; compare with a tolerance
64-bit IDs in JSON / JavaScript Send them as strings
Timestamps 64-bit; store in UTC; ISO 8601 for text
Text encoding UTF-8 everywhere; utf8mb4 in MySQL
Comparing user-visible text Normalize to NFC first
User-facing length limits Count grapheme clusters
Binary formats and network data State byte order explicitly

Every one of these rules exists because a bit pattern was read under the wrong assumption. Knowing the representation lets you see those bugs before they happen.

Copied to clipboard!