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

Workbench / Volume 1 Exercises: Foundations of Computing

V1·06

Number Systems and Data Representation

Exercises for Volume 1, chapter 06: place value and bases, binary, octal and hexadecimal and converting between them, unsigned and two's-complement integers, sign extension and truncation, integer types across languages, bitwise operations, IEEE 754 floating point (layout, special values, rounding, precision versus range), money and decimals, characters and encodings (ASCII, Unicode, UTF-8, UTF-16, UTF-32, BOM), byte order and alignment, variable-length integers, the 2⁵³ problem, serialisation compatibility and binary-to-text encodings. 13 theory questions, 12 programming exercises, 3 cumulative projects with chapters 01–05, the concepts the chapter leaves out, and 6 senior-level exercises.

41 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. This chapter is about what bits mean, so most exercises ask you to predict the exact output of a conversion or calculation before running it: if your prediction and the machine disagree, that's the gap to close. Real output comes from Java 21, Python 3.13 and Node 22 on a little-endian x86-64 machine.

Volume 23 covers text encodings for international products in depth; here the focus is how the representations work at the bit level and the bugs they cause in ordinary code.

Coverage map.

Chapter component Exercises
place value, bases, binary, hexadecimal, octal, converting T1, P1
unsigned integers; two's complement; sign extension and truncation T2, T3, P2
integer types across languages; overflow T3, P2, S1
bitwise operations and tricks T4, P3, P12
IEEE 754: scientific notation in binary, layout T5, P4
zero, infinity, NaN, subnormals T6, P4, P5
rounding and floating-point error; precision vs range T7, P5
money, decimals and fixed point T8, P6
ASCII, code pages, Unicode, code points, graphemes T9, P7
UTF-8, UTF-16, UTF-32, BOM; text in the languages; common text bugs T9, T10, P7
endianness; alignment in binary formats T11, P8
variable-length integers T12, P9
numbers across systems: JSON and 2⁵³; serialisation compatibility T13, P11, S3
binary-to-text encodings (hex, Base64) T12, P10

Theory

T1. Bases you meet every day

Convert by hand, showing the place values, and say where you'd meet each in real work:

  1. 255 to binary, octal and hex.
  2. The colour #1F6F78 to its red, green and blue values.
  3. File permission 0644 to decimal, and to rwx notation.
  4. 0x7FFFFFFF to decimal, and why it's significant.
  5. Why do programmers use hex rather than decimal to write bytes?

T2. Two's complement from first principles

  1. Explain how 8-bit two's complement represents −1, −56 and −128, and why the same circuit adds signed and unsigned numbers.
  2. Why does negating Integer.MIN_VALUE give Integer.MIN_VALUE, and why does Math.abs(Integer.MIN_VALUE) return a negative number?
  3. Explain sign extension: why does the byte 0xC8 become −56 when widened to int in Java, and how does b & 0xFF fix it?

T3. Integer types across languages, and what overflow does

For each language, say what INT_MAX + 1 does with its standard 32-bit integer type, and whether the result is defined: C (int), Java (int), Go (int32), Rust (i32, debug and release builds), Python (int), JavaScript (number). Then explain shifts: -16 >> 2 versus -16 >>> 2 in Java, and why -7 >> 1 differs from -7 / 2.

T4. Bit tricks with real uses

Explain how each works and give an everyday use:

  1. (x & (x - 1)) == 0 tests for a power of two.
  2. x & -x (or Integer.lowestOneBit) isolates the lowest set bit.
  3. Integer.bitCount(x) (population count).
  4. (h ^ (h >>> 16)) in Java's HashMap.
  5. A set of delivery days as 7 bits; adding, removing and testing a day.
  6. (n + 7) & ~7 rounds up to a multiple of 8.

T5. Inside a double

  1. Describe the IEEE 754 double layout (sign, exponent, fraction), the exponent bias, and the hidden leading 1. Decode the bits of 1.0 and 0.1 (P4).
  2. Why is 0.1 stored as 0.1000000000000000055511151231257827021181583404541015625?
  3. Why does (float) 16777217 give 16777216, and above what value can a double no longer represent every integer?

T6. Special values

Explain each, how it arises, and the bug it causes in ordinary code:

  1. −0.0 (P4: 0.0 == -0.0 is true but Double.valueOf(0.0).equals(-0.0) is false, and 1 / -0.0 is −Infinity).
  2. Infinity.
  3. NaN (P4: NaN == NaN is false; Double.compare(NaN, 1e308) is 1).
  4. Subnormal numbers, and why they can make arithmetic suddenly slow.

T7. Rounding error: where it comes from and how it grows

  1. Explain why (1e16 + 1) - 1e16 is 0.0 but (1e16 - 1e16) + 1 is 1.0 (P5). What does that say about associativity?
  2. Adding 0.1 ten million times gave 999999.9998389754 (P5). Explain the error's growth, and how Kahan (compensated) summation reached exactly 1000000.0.
  3. Precision vs range: a float reaches 3.4 × 10³⁸ but has only about 7 significant decimal digits. Give a real bug that comes from using float for a quantity that needs more digits (timestamps, coordinates, money).

T8. Money, decimals and fixed point

  1. Why is new BigDecimal(0.1) different from new BigDecimal("0.1") and BigDecimal.valueOf(0.1) (P6)?
  2. Why is new BigDecimal("2.0").equals(new BigDecimal("2.00")) false, and what bug does that cause in a HashSet or as a map key?
  3. Why does BigDecimal.ONE.divide(new BigDecimal(3)) throw, and how do you divide money correctly?
  4. Compare three representations for money: long minor units (paise), BigDecimal, and a database NUMERIC(12, 2). When would you use each?

T9. From characters to bytes

  1. Explain the difference between a character, a code point, a code unit and a byte, using A, é, ₹, 😀 and 👍🏽. Give each one's UTF-8 bytes, UTF-16 code units, Java length() and code-point count (P7 prints them).
  2. How does UTF-8 encode a code point in 1–4 bytes, and why can a decoder always find the start of a character?
  3. What's a BOM, and why does it sometimes break CSV headers and shell scripts?

T10. Text bugs in ordinary Java

Explain each result from P7, and the correct approach:

  1. new StringBuilder("ok👍🏽").reverse() gave 🏽👍ko.
  2. "ok👍🏽".substring(0, 3) printed ok?.
  3. "ok👍🏽".length() is 6, but a user sees 3 characters.
  4. A database column VARCHAR(10) in MySQL with utf8 (not utf8mb4) rejects an emoji.

T11. Byte order and binary formats

  1. What are big-endian and little-endian? P8 wrote 0x01020304 both ways: what bytes appeared?
  2. A file format stores lengths as 4-byte little-endian integers; your Java code reads them with DataInputStream.readInt(). What happens with the length 500 (P8)?
  3. What is "network byte order", and why do PNG, TCP/IP headers and Java's DataOutputStream use it while x86 and ARM CPUs (as usually configured) are little-endian?
  4. Why do binary formats specify alignment and padding, and what goes wrong when a C program writes a struct directly to a file and another machine reads it?

T12. Varints, Base64 and the cost of encodings

  1. How does a varint (LEB128, as Protocol Buffers uses) encode 1, 300 and 2³¹? Why does −1 take 10 bytes as a plain varint, and how does ZigZag encoding fix that (P9)?
  2. Base64 turns 3 bytes into 4 characters. How long is 30 bytes in hex and in Base64 (P10)? Why does 31 bytes become 44 characters? When must you use base64url instead of standard Base64?
  3. When should binary data go into JSON as Base64, and when shouldn't it go into JSON at all?

T13. Numbers between systems

  1. Using P11, explain why 9007199254740993 becomes 9007199254740992 in JavaScript and in a Java double, but not in Python's json.loads.
  2. What do JavaScript's JSON.parse and Python's json.loads do with 1e400? Why is that a problem for validation?
  3. Write the rules you'd put in an API style guide for numbers in JSON.

Programming exercises

P1. Bases and colours

In Java, print 255 in bases 2, 8, 16 and 36; parse "ff" as hex; print the decimal value of the octal literal 0644; and extract the RGB components of 0x1F6F78 with shifts and masks. Then write your own toBase(int n, int base) without library calls, and test it against Integer.toString(n, base) for 10,000 random values and bases.

P2. Signed, unsigned and shifts

Print, in Java: −1 in binary; ~5 + 1; -Integer.MIN_VALUE; the byte 0xC8 widened to int with and without & 0xFF; -16 >> 2, -16 >>> 2, -7 / 2, -7 >> 1; and 0xFFFFFFFF as signed, unsigned, divided unsigned by 2 and compared unsigned with 1.

P3. Bitmasks for real data

Represent delivery days as bits (Monday = bit 0). Set Monday, Wednesday and Saturday; print the mask, the number of days, whether Wednesday is set, and the lowest set bit. Then test isPowerOfTwo for 64 and 96, compute the next power of two ≥ 100 with Integer.highestOneBit, and write a loop that lists every set day by repeatedly clearing the lowest set bit.

P4. Look inside doubles

In Java, print the sign, exponent and the start of the fraction bits for 1.0, 0.1, −0.0, NaN, Infinity and Double.MIN_VALUE; the exact value of 0.1 via new BigDecimal(0.1); Math.ulp at 1, 1e6 and 1e16; whether 1e16 + 1 == 1e16; (long) 16777217f; and the equality and comparison behaviour of 0.0, −0.0 and NaN.

P5. Summation error and how to tame it

Sum 0.1 ten million times naively and with Kahan summation; print both. Compute (1e16 + 1) - 1e16 and (1e16 - 1e16) + 1. Then sum the same ten million values with DoubleStream.sum() (which uses compensated summation internally) and with long arithmetic in units of 0.1.

P6. BigDecimal traps

In Java: compare new BigDecimal(0.1) with new BigDecimal("0.1") and print BigDecimal.valueOf(0.1); test equals and compareTo for 2.0 and 2.00 and after stripTrailingZeros; divide 1 by 3 without and with a scale; round 2.345 to two places with HALF_EVEN and HALF_UP; print (double) 0.1f and 1.0f / 3 next to 1.0 / 3.

P7. Text as bytes, units and code points

For A, é, ₹, 😀 and 👍🏽, print the UTF-8 bytes, the UTF-16BE bytes, length() and codePointCount. Then reverse "ok👍🏽" with StringBuilder.reverse() and print substring(0, 3). Run with LANG=C.UTF-8 so the terminal shows the characters.

P8. Byte order in practice

Using ByteBuffer, write 0x01020304 big-endian and little-endian and print the bytes; print the native byte order; then write 500 as a little-endian int and read it back big-endian. Finally, read the width and height of a real PNG file (bytes 16–23 of the file, big-endian), for any PNG on your computer.

P9. Implement varints and ZigZag

Write varint(long v) (LEB128, as Protocol Buffers uses) and zigzag(long n) in Java. Print the encodings of 1, 127, 128, 300, 2³¹ and −1, and of ZigZag(−1). Then write the decoder and test that decode(encode(v)) = v for a million random longs, including negative ones.

P10. Hex, Base64 and base64url

Encode 30 random bytes as hex, standard Base64 and base64url without padding, and print the lengths; then encode 31 zero bytes in Base64 and print the length. Decode each back and check the bytes match. Finally, try decoding a base64url string containing - and _ with the standard decoder and observe the error.

P11. The same JSON in three languages

Parse [9007199254740993, 1e400, 0.1] with Node's JSON.parse, Python's json.loads, and (if you have Jackson available) Java with default settings and with USE_BIG_INTEGER_FOR_INTS / USE_BIG_DECIMAL_FOR_FLOATS. Print what each produced and check 2**53 + 1 === 2**53 in JavaScript and float(2**53 + 1) == 2**53 in Python.

P12. IP addresses as integers

Convert 192.168.12.34 to an unsigned 32-bit integer, and test whether it's in 192.168.0.0/16 and 192.168.0.0/24 with masks. Then write inCidr(String ip, String cidr) and test it with edge cases: /0, /32, 0.0.0.0, 255.255.255.255, and malformed input like 256.1.1.1 and 1.2.3.

Cumulative projects (chapters so far: 01–06)

C1. A binary log format with a reader and a fuzzer

Design and implement (in Java) a compact binary format for order events: a file header (magic bytes, version), then records of: varint length, event type (1 byte), order ID (8 bytes, little-endian), amount in paise (ZigZag varint), and a UTF-8 kitchen name (varint length + bytes), with a CRC32 per record. Write a writer, a reader that streams records from standard input and prints them as JSON lines (IDs as strings), and a fuzzer that corrupts random bytes of valid files and checks the reader never crashes, hangs or allocates more than a set limit: it must report corrupt records on stderr with their offset, skip or stop cleanly, and exit with code 2. Compare file size with the same data as JSON lines and as gzip-compressed JSON lines.

Combines: stdin/stdout/stderr, exit codes, files and bytes (ch 01); error handling, I/O, serialisation (ch 02); buffers and arrays (ch 03); complexity of streaming (ch 04); probability of undetected corruption with a 32-bit CRC (ch 05); varints, ZigZag, byte order, UTF-8, JSON number rules (ch 06).

C2. A money library that can't lose a paisa

Write a Java Money value type (a record) with long minor and a Currency (ISO 4217, with its minor-unit count: INR 2, JPY 0, KWD 3), and operations: add/subtract (same currency only, overflow-checked), multiply by a BigDecimal rate with an explicit RoundingMode, allocate by ratios (chapter 02's C4), parse from a decimal string (rejecting too many decimal places), and format for display with a Locale (Volume 23). Write property-based tests: allocation sums to the total; parse(format(m)) round-trips for locale-neutral formatting; currency mismatches throw; overflow throws instead of wrapping. Show that the same operations done with double drift.

Combines: exit codes for the test runner (ch 01); records, immutability, exceptions vs results, testing (ch 02); maps for currency data (ch 03); allocation algorithms (ch 04); invariants and proofs by property (ch 05); integers, overflow, BigDecimal, rounding modes, parsing (ch 06).

C3. Unicode-safe truncation and validation for a messaging feature

TiffinBox sends order updates by SMS and push (Volume 23's chapter 07). Write a Java utility that, given text and a channel, returns a message that fits: SMS single segment (160 GSM-7 characters or 70 UCS-2 units), push body (at most 4,096 bytes of UTF-8 in the JSON payload including escaping). It must: detect whether text fits GSM-7; truncate at grapheme boundaries (never splitting surrogate pairs, combining marks or emoji sequences) and add an ellipsis; reject or strip control and bidi-override characters; and report the encoded size. Test it with English, Hindi, Telugu, emoji with skin tones and family sequences, and strings near every limit.

Combines: bytes and streams (ch 01); strings and immutability (ch 02); iteration over sequences (ch 03); linear-time scanning (ch 04); counting limits exactly and edge-case reasoning (ch 05); UTF-8, UTF-16, surrogates, code points and graphemes (ch 06).

What the chapter leaves out

Checksums, CRCs and cryptographic hashes

The chapter mentions checksums briefly. Know the three tiers: simple checksums and CRCs (CRC32, Adler-32) detect accidental corruption (bit flips, truncation: measured, a single flipped bit changed the CRC32) and are fast enough for every disk block and network packet; but CRCs are linear (measured: crc(a ⊕ b ⊕ c) = crc(a) ⊕ crc(b) ⊕ crc(c) for equal-length inputs), so anyone can modify data and fix up the CRC. Cryptographic hashes (SHA-256, BLAKE3) make finding collisions infeasible: use them for content addressing (Git), de-duplication and integrity of downloads. MACs (HMAC-SHA-256) add a secret key, so only key holders can produce a valid tag: use them for webhook signatures, signed URLs and cookies. Choosing CRC where an attacker is involved, or a bare hash where a MAC is needed, are classic mistakes (Volume 10).

Compression and entropy

Representation choices interact with compression. Repetitive data compresses well (measured: a 448,910-byte CSV of orders gzipped to 54,665 bytes, 12%), while random or encrypted data doesn't compress at all (measured: 448,910 random bytes became 449,068: slightly larger). Consequences: compress before encrypting (afterwards it's pointless); don't gzip already-compressed formats (JPEG, PNG, ZIP, video); columnar formats (Parquet) compress far better than row formats because similar values sit together; and compressing secrets alongside attacker-controlled data can leak them through the compressed size (the CRIME and BREACH attacks on TLS and HTTP compression).

Identifiers as data representation

How you represent IDs affects performance and safety. Random UUIDv4 values (122 random bits; chapter 05's T11) are unguessable but scatter inserts across a B+ tree index, causing page splits and poor cache locality in databases. Time-ordered IDs (UUIDv7, ULID, Twitter's Snowflake: a timestamp in the high bits plus randomness or a sequence) insert at the "end" of the index like auto-increment keys while staying globally unique. Store UUIDs as 16-byte binary (or the database's UUID type), not 36-character strings (more than twice the size, slower comparisons). Python 3.13's uuid module, for example, has no uuid7 yet (checked), so libraries or your own implementation fill the gap; standards for UUIDv7 were finalised in RFC 9562 (2024).

Time as a number

Timestamps are integers with units, and unit mistakes are common: Unix time in seconds (a 32-bit signed counter overflows in 2038), milliseconds (Java's currentTimeMillis, JavaScript's Date.now), microseconds (PostgreSQL), or nanoseconds (Instant has nanosecond fields; a nanosecond count overflows a long in 2262 and exceeds 2⁵³, so it's unsafe in JSON numbers). Mixing seconds and milliseconds gives dates in 1970 or the year 50,000. Always name the unit in field names (createdAtMs) or use ISO 8601 strings at boundaries, and handle time zones as Volume 23's chapter 03 describes.

Reduced-precision numbers in machine learning

ML systems use 16-bit and smaller floating-point types: float16 (5 exponent bits, 10 fraction bits: small range, overflows above 65,504), bfloat16 (8 exponent bits like float32, but only 7 fraction bits: float32's range with about 2–3 significant digits), and 8-bit and 4-bit quantised integers. They halve or quarter memory and bandwidth, which is why model weights fit on GPUs at all. The trade-offs are exactly this chapter's: precision versus range, rounding error accumulation (training uses higher-precision accumulators), and overflow (loss scaling). If you work with AI systems (Volume 14), you'll meet them.

Parsing untrusted binary data

Every length, count and offset field in a binary format is attacker-controlled when the file comes from outside. Unvalidated, they cause huge allocations (a length of 2³¹), integer overflow in size calculations (count * elementSize wrapping to a small number, then a buffer overflow in native code), infinite loops (varints without a length limit, P9), and out-of-bounds reads. Many famous vulnerabilities in image, font and media parsers are exactly this. Validate every field against the remaining input and sane maximums, use overflow-checked arithmetic (Math.multiplyExact), and fuzz your parsers (C1).

Senior exercises

S1. Hunting an overflow in production code

A file upload service reports "uploaded 2.1 GB of 3.4 GB" progress correctly until 2 GB, then shows negative numbers, and some uploads over 4 GB are stored truncated with no error. The code uses int bytesRead, int contentLength = Integer.parseInt(header), and computes percent = bytesRead * 100 / contentLength. Find every overflow, explain each symptom bit by bit, and write the fix and the tests. Then describe how you'd find similar bugs across the codebase.

S2. Floating point in a pricing engine

A pricing engine computes price = base * (1 + gst) * (1 - discount) in double, rounds with Math.round(price * 100) / 100.0, and finance reports that invoices differ from the ledger by a paisa on about 1 in 2,000 orders. Explain the mechanisms (T5–T8), including why Math.round(x * 100) / 100.0 isn't reliable, and redesign the calculation with exact arithmetic and an explicit rounding policy. How would you migrate without changing prices customers have already seen?

S3. An API that loses digits

A partner integration sends you order IDs as JSON numbers (64-bit values from their database), and your Node.js gateway forwards them to a Java service. Some orders can't be found. Using T13 and P11, diagnose it, explain why it only affects some orders, and design both an immediate fix and a long-term contract. Include how you'd find already-corrupted records.

S4. Choose a serialisation format

Three teams ask you to pick a format: (1) the mobile apps' public API (Volume 22), (2) 2 million events per second between internal services, and (3) the analytics data lake queried by SQL. Compare JSON, Protocol Buffers, Avro and Parquet on: size, speed, schema evolution, readability, language support and tooling, and the number representation issues from this chapter. Recommend one per case and justify it.

S5. Review a binary parser

A colleague wrote a Java parser for a vendor's binary price file: it reads a 4-byte count with DataInputStream.readInt(), allocates new Price[count], then for each price reads a 2-byte name length with readShort(), allocates new byte[len], reads the name and decodes it with new String(bytes), then reads an 8-byte double price. Find every bug and risk using this chapter, rank them, and write the review.

S6. Teach representation with one surprising demo

You have 10 minutes at a team meeting to convince engineers that "numbers aren't what they look like". Choose three demonstrations from this chapter's programming exercises that together cover integers, floating point and text, explain why each will surprise this audience (Java backend developers), and write the one-sentence takeaway for each. Then say what you'd change in the team's code-review checklist as a result.