Volume 1 Companion: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Companion: Foundations of Computing

V1·06

Data Representation

Companion to Volume 1, chapter 06: how integers, real numbers and text-on-the-wire connect; new angles (a car's odometer as two's complement, a ruler whose markings thin out as floating point, PIN codes as prefix codes, dates as byte order, lakh and crore as another way to group the same digits); what the chapter simplifies, from a division that crashes a C program with a "floating point exception" to Java parsing Devanagari digits and rounding −2.5 to −2; the theory behind it (rings, error bounds and conditioning, prefix codes, counting the doubles); the JDK's `Integer.parseInt` and compact strings; four debugging drills; interview questions with how to approach each.

6 sections · ~18 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 06 has three strands. Integers are bit patterns read in base 2, with a convention (two's complement) for negatives. Real numbers are approximated by floating point, which trades exactness for range. Text and bytes on the wire are the conventions for turning characters and numbers into byte sequences that other programs can read.

integers real numbers text and bytes on the wire positional systems base · place value binary, hex 4 bits = 1 hex digit unsigned integers 0 … 2ⁿ − 1 two's complement mod 2ⁿ · one extra negative overflow, conversions wrap · trap · saturate bitwise operations masks · shifts binary scientific notation significand × 2ᵉ IEEE 754 sign · exponent · fraction special values ±0 · ∞ · NaN · subnormal rounding error 0.1 isn't 0.1 precision vs range gaps grow with size decimals, fixed point integer paise Unicode code points · graphemes UTF-8, UTF-16 variable-length units byte order big · little endian varints, formats compact · versioned numbers across systems JSON and 2⁵³ binary-to-text hex · Base64 base 2, 16 n bits reinterpret edges in 64 bits reserved worse when large so use encode units between systems fractions fields goes deeper: ch5 modular arithmetic · ch7 how the CPU adds and stores these · ch9 bytes on the network Volume 4: column types and collations · stage 6 of the TiffinBox build: a versioned binary order record
Concept map of chapter 06: numbers as bits (positional systems, binary and hex, unsigned and two's complement integers, overflow, bitwise operations), real numbers (IEEE 754 floating point, special values, rounding error, decimals and fixed point for money) and text and bytes on the wire (Unicode code points, UTF-8 and UTF-16, byte order, variable-length integers, serialisation and binary-to-text encodings), with links such as two's complement being arithmetic modulo 2^n and money needing fixed point because binary fractions can't represent 0.1.

The links worth remembering:

  • The same bits, read differently. 0xFFFFFFFF is 4,294,967,295 unsigned, −1 in two's complement, NaN as a float, and four bytes of invalid UTF-8. Representation is always bits plus an agreement about how to read them, and most bugs in this chapter are two parts of a system disagreeing about the agreement.
  • Two's complement is modular arithmetic. Adding, subtracting and multiplying ints is arithmetic mod 2³² (the Companion to chapter 05, theoretical gap 6). Overflow isn't a malfunction; it's the modulus showing.
  • Money needs fixed point because of rounding, and rounding is a rule. Binary fractions can't hold 0.1, so money is integers of the smallest unit; then every division needs a rounding rule, which is a business decision (Gaps 4).

Explain it differently

1. Two's complement is a car's odometer. A three-digit odometer at 000 rolled back one kilometre shows 999. If you agree that readings from 500 to 999 mean "−500 to −1", then 999 is −1, and adding works without any special cases: 999 + 2 rolls over to 001, which is −1 + 2 = 1. That's two's complement in base 10. It also shows the asymmetry: the readings 500–999 give 500 negatives, but 001–499 give only 499 positives, so −500 has no positive partner. Negating it gives −500 again (Gaps 1).

2. Floating point is a ruler whose markings thin out. Near zero the markings are packed incredibly close; far from zero they spread apart, doubling their spacing at every power of two. Counting real bit patterns (computed from the IEEE 754 layout):

Range Number of doubles
[0, 1) 4,607,182,418,800,017,408
[1, 2) 4,503,599,627,370,496
share of all positive finite doubles below 1 50.0%

Half of all positive doubles lie between 0 and 1, and [1, 2) has about a thousand times fewer than [0, 1). The relative precision is the same everywhere (about 16 significant digits); the absolute gap grows with size. That's why adding ₹0.01 to ₹10¹⁶ does nothing (Chapter Exercises T5).

3. UTF-8 is a set of PIN codes where no code starts another. Indian postal PINs are all six digits, so a sorter never wonders where one ends. UTF-8 codes vary in length, so it uses a different trick: the first byte says how long the code is (0xxxxxxx is one byte, 110xxxxx starts two, 1110xxxx three), and continuation bytes look different (10xxxxxx). No valid code is the beginning of another, which makes it a prefix code (theoretical gap 3). Varints in the chapter use the same idea with one "more bytes follow" bit.

4. Byte order is date format. 14/11/2026 and 11/14/2026 and 2026-11-14 hold the same three numbers in different orders. Big-endian is 2026-11-14: biggest part first, so sorting the text sorts the dates. Little-endian is 14/11/2026: smallest part first. Neither is wrong; the bug is when the writer and reader disagree, which is exactly when 3 November and 11 March swap places.

5. Lakh and crore are the same digits, grouped differently. 123456789 is 123,456,789 in the international system and 12,34,56,789 in the Indian one: same base, same place values, different presentation. Representation (what the number is) and formatting (how it's shown) are separate layers, and code that mixes them breaks for some users. Java's own DecimalFormat can't do the Indian grouping at all (Gaps 3).

6. Hexadecimal is reading a phone number in chunks. 98490 12345 is easier to read than 9849012345 because each chunk is small. Hex groups binary in fours: 1101 0110 is D6. Every hex digit is exactly 4 bits, so a byte is always 2 hex digits, a 32-bit int is 8, and you can read bits from hex in your head. Decimal doesn't line up with bits at all, which is why memory dumps, colours and hashes are written in hex.

7. Overflow has three personalities. Exceeding a type's range can wrap (Java int addition: like the odometer), trap (Rust in debug builds panics; C's integer division by −1 kills the process), or saturate (Java converting a too-large double to int sticks at the maximum). And in C, signed overflow is undefined, which is a fourth personality: whatever the optimiser decides. The same program can show all of them in a few lines (Gaps 1 and 2).

8. A character is a number with a passport. The letter "३" (Devanagari three) is the code point U+0969. It is a digit in Unicode (Character.isDigit says yes), with the numeric value 3. Whether your program treats it as a digit depends on which function you call, not on the character (Gaps 3; drill D1).

Gaps and misconceptions

What the chapter oversimplifies

1. "Overflow happens when you add or multiply past the range": division and negation overflow too. There's one more negative int than positive, so Integer.MIN_VALUE has no positive counterpart. Real output:

Terminal
Integer.MIN_VALUE / -1 = -2147483648, Math.negateExact: java.lang.ArithmeticException: integer overflow

Java wraps silently: dividing the most negative number by −1 gives the most negative number. C does something else entirely. The same division compiled with GCC 13 on x86-64:

Terminal
dividing -2147483648 by -1...
Floating point exception
exit status 136

The process is killed by SIGFPE (signal 8; 128 + 8 = 136), named "floating point exception" for historical reasons although no floating point is involved: the CPU's integer divide instruction traps on this one input, as it does on division by zero. One input in four billion squared can crash a C service, which is why fuzzers try INT_MIN and −1 first.

2. "Converting between types may lose information": Java uses two different rules. Narrowing an integer wraps (keeps the low bits); narrowing a floating-point number saturates (clamps to the range):

Terminal
(int) 1e10 = 2147483647, (int) -1e10 = -2147483648, (int) NaN = 0, (long) Infinity = 9223372036854775807, (byte) 200 = -56, (int) 3_000_000_000L = -1294967296

So 3 billion as a long becomes about −1.29 billion as an int, while 10 billion as a double becomes 2.147 billion, and NaN quietly becomes 0. In C, converting an out-of-range double to int is undefined behaviour; Python refuses (int(float("inf")) raises OverflowError: cannot convert float infinity to integer). Neither Java rule is an error you'll see. Use Math.toIntExact for long to int, and check the range (and NaN) before converting a double (drill D2).

3. "Characters are numbers too": and parsers disagree about which numbers are digits. The chapter treats digits as '0'–'9'. Unicode has dozens of digit sets (Devanagari, Arabic-Indic, Tamil, Bengali, fullwidth…), and libraries disagree about accepting them:

Terminal
Integer.parseInt("३४") = 34, Integer.parseInt("٣٤") = 34, "३४".matches("\\d+") = false, Character.isDigit('३') = true
Python: int("३४") = 34 | re \d matches "३४": True | re.ASCII: False | round(2.5) = 2 round(3.5) = 4 round(-2.5) = -2
JS: Math.round(2.5) = 3 Math.round(-2.5) = -2 | parseInt("३४") = NaN | /^\d+$/.test("३४") = false

Java's parseInt accepts Devanagari and Arabic-Indic digits, but Java's regex \d doesn't match them. Python's \d does (unless you pass re.ASCII), and so does int(). JavaScript accepts neither. So a Java service validating with a regex and a Python service validating with \d disagree on the same input. Formatting goes the other way: the TiffinBox build's stage 1 printed {"count":३,...} under a Marathi locale. Validate with an explicit [0-9], and format machine-readable output with Locale.ROOT.

Formatting has a second surprise. India groups digits as 12,34,56,789, and the JDK's locale data knows it, but java.text.DecimalFormat supports only one grouping size:

Terminal
en-IN pattern from CLDR via DecimalFormat: #,##0.### -> 123,456,789
applyPattern("#,##,##0") -> 123,456,789
JS Intl en-IN: 12,34,56,789 | hi-IN-u-nu-deva: १२,३४,५६,७८९

Even an explicit #,##,##0 pattern prints 123,456,789: the Javadoc says only the interval between the last grouping separator and the end is used. Browsers (Intl.NumberFormat) and ICU4J get it right. For Indian users, format on the client or use ICU.

4. "Round half up" isn't one rule, and none of the common ones is symmetric about zero. The chapter uses RoundingMode.HALF_EVEN for money. The everyday functions each pick a different rule:

Terminal
Math.round(2.5) = 3, Math.round(-2.5) = -2, Math.round(-3.5) = -3, Math.rint(2.5) = 2.0

Java's Math.round (and JavaScript's) rounds halves toward positive infinity: 2.5 → 3 but −2.5 → −2. Python's round and Java's Math.rint round halves to even. So rounding credits and debits with Math.round doesn't cancel:

Terminal
1,000 pairs of +x.5 and -x.5: exact sum 0.0, sum of Math.round = 1000

Exact total zero; rounded total 1,000. Each pair drifts by one unit in the same direction (drill D3). For money, round once, with an explicitly named RoundingMode, on integers or BigDecimal.

Common misconceptions

Misconception What's actually true Where it's shown
"Only addition and multiplication overflow." Negation, abs, and MIN_VALUE / -1 overflow too; in C the division kills the process. Gaps 1
"A cast to a smaller type keeps the low part." For integers. For floating point, Java saturates and NaN becomes 0. Gaps 2; drill D2
"Character.isDigit and [0-9] agree." isDigit accepts hundreds of Unicode digits. Gaps 3; drill D1
"Rounding is symmetric." Math.round(-2.5) is −2 while Math.round(2.5) is 3. Gaps 4; drill D3
"A char in an expression is a character." In arithmetic it's promoted to an int code: 'A' + 1 is 66. drill D4
"Formatting with the locale's grouping is a one-liner." DecimalFormat can't produce Indian grouping. Gaps 3

Theoretical gaps: the ideas behind the chapter

1. Fixed-width integers form a ring, not the integers. n-bit integers with wrapping addition and multiplication are the integers mod 2ⁿ (ℤ/2ⁿℤ). Every ring law holds: addition and multiplication are associative and commutative, and multiplication distributes. That's why compilers may reorder integer arithmetic freely (unlike floats), and why (a + b) - b == a always holds even when a + b overflows: the overflow cancels mod 2ⁿ. What doesn't hold is order: in ℤ/2ⁿℤ, "bigger" has no meaning compatible with addition, so a + 1 > a can be false. Signed and unsigned are two ways of choosing representatives (−2ⁿ⁻¹…2ⁿ⁻¹−1, or 0…2ⁿ−1) for the same ring, which is why the CPU uses the same add instruction for both.

2. Floating-point error has a bound, and problems have a condition number. IEEE 754 guarantees each basic operation is correctly rounded: fl(a ∘ b) = (a ∘ b)(1 + δ) with |δ| ≤ u, where u = 2⁻⁵³ ≈ 1.1 × 10⁻¹⁶ for doubles. That single fact lets you bound the error of a whole computation. Whether the final answer is accurate then depends on the problem's condition number: how much the exact answer changes when inputs change slightly. Subtracting nearly equal numbers is ill-conditioned (a tiny relative input error becomes a huge relative output error), which is what "catastrophic cancellation" really is. An algorithm is backward stable if its result is the exact answer for slightly perturbed inputs. Good numerical code is backward-stable algorithms applied to well-conditioned problems; neither alone is enough.

3. Variable-length encodings are prefix codes. UTF-8, varints and Huffman codes share one property: no codeword is a prefix of another, so a stream can be decoded without separators. The Kraft inequality (Σ 2^(−length) ≤ 1) says which sets of lengths are possible, and Shannon's source-coding theorem says the best average length is the entropy of the symbol distribution. UTF-8 is a compromise: short codes for ASCII (common in markup and code) at the cost of 3 bytes for most Indian scripts, where UTF-16 uses 2. Representation choices are bets on the distribution of your data.

4. Every finite representation is a lossy map from an infinite set. There are infinitely many integers and reals, and 2⁶⁴ bit patterns. So every representation chooses which values to represent exactly and how to map the rest: integers drop everything past the range (and wrap), floats keep about 16 significant digits at any scale, decimals keep exact tenths and hundredths but not thirds. The design question is never "is it exact?" but "exact for which values my domain needs?" For money in paise, integers are exact for every value TiffinBox can hold.

5. Representation and presentation are different layers. The number 123456789, the string "12,34,56,789", the bytes 07 5B CD 15 and the JSON token 123456789 are four layers: value, human presentation, binary representation, interchange format. Bugs come from crossing layers without a conversion: formatting with a locale into a file a machine reads (stage 1's ३), parsing human input with a machine parser (drill D1), or treating JSON numbers as doubles (Chapter Exercises P11). Good design names the layer at every boundary: Locale.ROOT for machines, the user's locale for people.

6. Text identity is a choice of equivalence relation. The chapter shows NFC normalisation. More generally, "are these two strings the same?" can mean byte equality, code-point equality, canonical equivalence (NFC/NFD), compatibility equivalence (NFKC: "fi" equals "fi", "²" equals "2"), case-insensitive equivalence (which depends on locale: Turkish dotless i), or "same to a human" (confusables: Latin "a" and Cyrillic "а"). Each is an equivalence relation (the Companion to chapter 05), and choosing the wrong one gives duplicate accounts or spoofed usernames. Usernames typically need NFKC plus case folding plus a confusables check.

Applying it

Code walkthrough

Two pieces of java.lang show the chapter's representation choices in production code. Excerpts from jdk-21-ga.

Integer.parseInt: accumulating negatively

java/lang/Integer.java:

Java
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+') {
                    throw NumberFormatException.forInputString(s, radix);
                }

                if (len == 1) { // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s, radix);
                }
                i++;
            }
            int multmin = limit / radix;
            int result = 0;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                int digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0 || result < multmin) {
                    throw NumberFormatException.forInputString(s, radix);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s, radix);
                }
                result -= digit;
            }
            return negative ? result : -result;

Three ideas from the chapter, in fifteen lines:

  1. It builds the number as a negative. "−2147483648" must parse, but +2147483648 doesn't fit in an int. Accumulating towards negative and flipping the sign at the end handles MIN_VALUE without any special case: the negative range is one larger (Explain it differently 1).
  2. It checks for overflow before it happens. result < multmin means "multiplying by the radix would go past the limit"; result < limit + digit means "subtracting this digit would". Both comparisons are written so that they can't themselves overflow. This is how to write overflow-safe arithmetic without Math.multiplyExact.
  3. Character.digit decides what a digit is. That one call is why parseInt("३४") returns 34: Character.digit accepts any Unicode character with a decimal digit value (Gaps 3). The firstChar < '0' test for a sign is ASCII-only, though, so a leading sign must be an ASCII - or +.

Compact strings: one byte[], two encodings

java/lang/String.java:

Java
    public int length() {
        return value.length >> coder();
    }
Java
    byte coder() {
        return COMPACT_STRINGS ? coder : UTF16;
    }

Since Java 9 (JEP 254), a String stores its characters in a byte[] value with a coder field: LATIN1 (0) if every character fits in one byte, UTF16 (1) otherwise. length() is the byte count shifted right by the coder: divided by 1 for Latin-1, by 2 for UTF-16. So:

  • length() counts UTF-16 code units, whatever the storage, because that's what it has always promised. An emoji is 2, "é" in NFD is 2 (Chapter Exercises P7 and T10 go into this).
  • Memory depends on the content. "Masala dosa" takes 11 bytes of characters; "మసాలా దోస" (Telugu) takes 2 bytes per UTF-16 unit, and one Telugu letter anywhere in a long string makes the whole string UTF-16. A string's representation is chosen per string, at creation.
  • The comparison in the Companion to chapter 04 (StringLatin1.compareTo using ArraysSupport.mismatch) exists because of this split: Latin-1 strings can be compared as plain bytes.

Read it yourself

  1. Why does parseInt compute multmin = limit / radix once, before the loop, instead of checking result * radix < limit inside it?
  2. What does "abc".length() return, and how many bytes does its value array have? And for "aబc"?

Debugging drills

D1. An order for "२" plates

The CSV import accepts quantities checked like this:

Java
if (field.chars().allMatch(Character::isDigit)) qty = Integer.parseInt(field);
else reject(line);

An export from a spreadsheet set to Marathi produced a quantity of २. The import accepted it as 2. The reporting service, written in Python with re.fullmatch(r"\d+", field) and int(field), also accepted it. The database's CHECK constraint quantity ~ '^[0-9]+$' on a staging text column rejected it, and the nightly load failed. Explain, and decide what the system should do.

Terminal
Integer.parseInt("३४") = 34, Integer.parseInt("٣٤") = 34, "३४".matches("\\d+") = false, Character.isDigit('३') = true

D2. A ₹21,474,836.47 order

Prices from a partner feed arrive as rupee strings and are converted with:

Java
int paise = (int) (Double.parseDouble(rupees) * 100);

A bad feed sent "1e8" for one dish. The order total became ₹21,474,836.47, which passed every "positive amount" check. Explain, and rewrite the conversion.

Terminal
(int) 1e10 = 2147483647, (int) -1e10 = -2147483648, (int) NaN = 0, ...

D3. The refund ledger that never balances

A ledger stores adjustments in rupees as doubles and rounds each to whole rupees with Math.round when posting: credits like +2.5 and matching debits like −2.5. After a month, the "net zero" adjustments total +₹1,000 for a thousand pairs:

Terminal
Math.round(2.5) = 3, Math.round(-2.5) = -2, Math.round(-3.5) = -3, Math.rint(2.5) = 2.0
1,000 pairs of +x.5 and -x.5: exact sum 0.0, sum of Math.round = 1000

Explain, and say what you'd change in the design, not just the function.

D4. Table labels that say "66-3"

The kitchen display labels seats by row letter and seat number:

Java
char row = 'A'; int seat = 3;
String label = row + 1 + "-" + seat;   // meant "B-3"
Terminal
row + 1 + "-" + seat = 66-3 | (char) (row + 1) + "-" + seat = B-3

Explain the 66.

Career-oriented

Interview prep

Mid level

Q1. What's the output of System.out.println(0.1 + 0.2 == 0.3) and why? How would you compare two doubles correctly, and when shouldn't you use doubles at all?

How to get there. Give the answer, the reason in one sentence (binary fractions), then the technique (tolerance, relative not absolute), then the judgement (money and counts use integers or decimals).

Q2. How does UTF-8 encode "₹", and how would you find the number of characters a user sees in a Java string?

How to get there. Work it out from the bit pattern: code point, which byte-length bracket, fill in the bits. Then separate the three counts (bytes, UTF-16 units, code points) from user-perceived characters (grapheme clusters), and name the Java API for each.

Senior level

Q3. Your API sends order totals as JSON numbers in rupees with decimals ("total": 1234.5). A partner's JavaScript client sometimes shows ₹1234.49. What's happening, and how do you fix the contract without breaking existing clients?

How to get there. Diagnose (binary floats somewhere in the chain, and formatting with truncation), then fix the contract (integers of the minor unit, or decimal strings), then plan compatibility (additive fields, versioning, deprecation).

Q4. Design the on-disk representation for 10 billion events a day where each has a timestamp, an order id, a kitchen id, an event type and an amount. What choices matter most, and how do you justify them?

How to get there. Work out the volume first (bytes per event × 10¹⁰), then go field by field choosing the smallest exact representation, then the layout (row against column) and compression, then evolution (versioning). Numbers make it convincing.

Staff level

Q5. Your organisation operates in 12 countries. Bugs keep appearing with locales: digits, decimal separators, grouping, currency, sorting names. How do you fix this class of problem across many teams?

How to get there. Separate the machine layer (one fixed format) from the human layer (the user's locale), make the machine layer the default everywhere, centralise the human layer, and test with hostile locales. A staff answer changes defaults and tooling rather than fixing bugs one at a time.

Q6. A team proposes replacing JSON with a binary format (Protocol Buffers) for all internal service traffic to "save bandwidth". How do you evaluate it?

How to get there. Quantify the benefit first (is bandwidth or parsing actually a cost?), then list the costs (tooling, debugging, schema management, migration), then recommend a scoped decision with a measurement.