Mathematics Book 1 Companion: Arithmetic and NumbersMaths Book 1 · Companion
0 / 0

Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers

B1·02

Place Value and Bases

Around chapter 2: where place value shows up in software, three other ways to see it, what the chapter simplifies (leading zeros and octal, negative numbers in bits, formatting), how Python's ipaddress module reads an IP address as a base-256 numeral and why it refuses leading zeros, four debugging drills, and interview questions.

6 topics · ~11 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Bundling in groups of the base → place value: a digit's value is digit × base^position → expanded form.
  • Zero holds empty places; digits below the base make every numeral unique (proved by repeated division).
  • Counting is an odometer: roll over and carry (chapter 3's column addition is the same carry).
  • Bases: 10 for people, 2 for circuits, 8 and 16 as readable shorthand for bits (because 8=23, 16=24), 60 for time and angles, mixed radix for calendars.
  • Converting: repeated division (remainders, last digit first) and Horner's method (× base, + digit). The same two loops appear in every number parser and printer.
  • Length: k-digit numbers run from bk−1 to bk−1; a number has ⌊logbn⌋+1 digits (logarithms in chapter 10).
  • In software: integer types are fixed-width binary numerals (Software Engineering, Volume 1, chapter 06); IP addresses, colours and file modes are numerals in bases 256, 16 and 8; text formats (JSON, CSV, locales) decide how numerals are written.

Explain it differently

Money in notes. Paying ₹3,407 with ₹1,000, ₹100, ₹10 and ₹1 notes takes 3, 4, 0 and 7 of each: the numeral is the instruction "how many of each note". A shopkeeper who has no ₹10 notes left still writes the 0; the price doesn't change.

A car's trip meter in another base. Imagine a trip meter whose wheels have only the digits 0 to 4. It reads 0, 1, 2, 3, 4, then 10, and a person reading it in base 10 would think the car went from 4 km to 10 km in one kilometre. Every base is the same machine with a different number of positions on each wheel.

Addresses on a street. A number in base 256 is like an address written as "building 192, floor 168, flat 1, room 10": each part has its own range (0 to 255), and the full address is one number made of four digits. That's literally what an IPv4 address is, as the code walkthrough shows.

Gaps and misconceptions

What the chapter oversimplifies

1. "A leading zero changes nothing", but some software reads it as octal. In C and in older JavaScript, a numeral starting with 0 was read in base 8: 010 meant eight. Modern formats refuse the ambiguity instead of guessing. Measured in Python:

Python
import json
try:
    json.loads('{"phone": 04428112233}')
except json.JSONDecodeError as e:
    print("JSON refuses a leading zero:", e)
print(int("04428112233"), int("08", 10))
try:
    eval("04428112233")
except SyntaxError as e:
    print("Python source refuses it too:", e.msg)
Text
JSON refuses a leading zero: Expecting ',' delimiter: line 1 column 12 (char 11)
4428112233 8
Python source refuses it too: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

JSON's grammar doesn't allow a number to start with 0, Python source code refuses 04428112233 and points you to 0o for octal, while int() on a string quietly drops the leading zero (and loses the phone number's trunk prefix, chapter 1's drill). Three tools, three policies for the same digits. The code walkthrough shows a case where the ambiguity was a security bug.

2. "Binary is how computers store numbers", but negative numbers aren't just a minus sign. Python prints format(-5, "b") as -101, a minus sign and the binary for 5, which is how a person writes it. The machine stores a fixed-width pattern instead:

Text
-101 11111011 -0b101 fb
251 -5

(The first line is format(-5, "b"), format(-5 & 0xFF, "08b"), bin(-5) and (-5).to_bytes(1, "big", signed=True).hex(); the second reads the pattern 11111011 back as unsigned and as signed.) In 8 bits, −5 is stored as 11111011, which is also how 251 is stored. Which one it "is" depends on how it's read: two's complement, chapter 9's subject and chapter 3's subtraction-by-complement.

3. "Grouping is a reading aid", but formatting functions bake one convention in. Python's format language groups by threes only: f"{1234567.891:,.2f}" gives 1,234,567.89, and f"{1234567:_}" gives 1_234_567. There's no format code for Indian grouping (1,23,45,678); it has to be written by hand or with a locale library. Whatever a program prints, someone is reading it in a convention they may not share.

Common misconceptions

Misconception What's actually true Where it's shown
"A leading zero never changes a number's value." In C, older JavaScript and the C library's inet_aton, a leading 0 means octal: 010 is 8. What the chapter oversimplifies, point 1; code walkthrough
"An IP address is four separate numbers." It's one 32-bit number written as four base-256 digits; 192.168.1.10 is 3,232,235,786. Code walkthrough
"Negative binary numbers are a minus sign and the bits." Machines store a fixed-width two's complement pattern; 11111011 is −5 or 251 depending on how it's read. What the chapter oversimplifies, point 2
"Sorting numbers stored as text works." Text sorts character by character: "10" comes before "9". Debugging drill D3
"parseFloat reads a number with commas." It stops at the first comma: parseFloat("1,000") is 1. Debugging drill D2

Theoretical gaps: the ideas behind the chapter

  • Positional notation is a polynomial. dkbk+⋯+d1b+d0 is a polynomial in b with the digits as coefficients. Horner's method is the standard way to evaluate any polynomial, and arithmetic on numerals (carrying) is polynomial arithmetic followed by tidying the coefficients back into the range 0 to b−1. Algebra (beyond this book) builds on this.
  • Uniqueness is what makes comparison and sorting by numeral possible: two numerals of equal length compare digit by digit from the left only because each number has one numeral.
  • Information: k digits in base b distinguish bk things, so it takes log2N bits to tell N things apart. That's the root of "a byte holds 256 values" and of information theory.

Applying it

Code walkthrough

Python's ipaddress module turns an IPv4 address like 192.168.1.10 into a single integer and back. An IPv4 address is a four-digit numeral in base 256, written with each digit in decimal and dots between, exactly as clock time writes base-60 digits with colons. Excerpts from Lib/ipaddress.py in Python 3.13 (on your computer: python3 -c "import ipaddress; print(ipaddress.__file__)").

From text to a number

Python
    def _ip_int_from_string(cls, ip_str):
        """Turn the given IP string into an integer for comparison.

        Args:
            ip_str: A string, the IP ip_str.

        Returns:
            The IP ip_str as an integer.

        Raises:
            AddressValueError: if ip_str isn't a valid IPv4 Address.

        """
        if not ip_str:
            raise AddressValueError('Address cannot be empty')

        octets = ip_str.split('.')
        if len(octets) != 4:
            raise AddressValueError("Expected 4 octets in %r" % ip_str)

        try:
            return int.from_bytes(map(cls._parse_octet, octets), 'big')
        except ValueError as exc:
            raise AddressValueError("%s in %r" % (exc, ip_str)) from None

The four parts are parsed into four "digits", each 0 to 255, and int.from_bytes(..., 'big') combines them most significant first: that is Horner's method in base 256, ((192×256+168)×256+1)×256+10. Going back, _string_from_ip_int is one line: '.'.join(map(str, ip_int.to_bytes(4, 'big'))), repeated division by 256 done by to_bytes. Measured:

Python
import ipaddress, socket
a = ipaddress.ip_address("192.168.1.10")
print(int(a), hex(int(a)), 192 * 256**3 + 168 * 256**2 + 1 * 256 + 10)
print(ipaddress.ip_address(3232235786), ipaddress.ip_address("192.168.1.10") + 1)
for s in ["010.0.0.1", "127.1", "0x7f.0.0.1"]:
    try:
        print(s, "-> inet_aton:", socket.inet_aton(s).hex(".", 1), end="   ")
    except OSError as e:
        print(s, "-> inet_aton error:", e, end="   ")
    try:
        print("ipaddress:", ipaddress.ip_address(s))
    except ValueError as e:
        print("ipaddress error:", e)
Text
3232235786 0xc0a8010a 3232235786
192.168.1.10 192.168.1.11
010.0.0.1 -> inet_aton: 08.00.00.01   ipaddress error: '010.0.0.1' does not appear to be an IPv4 or IPv6 address
127.1 -> inet_aton: 7f.00.00.01   ipaddress error: '127.1' does not appear to be an IPv4 or IPv6 address
0x7f.0.0.1 -> inet_aton: 7f.00.00.01   ipaddress error: '0x7f.0.0.1' does not appear to be an IPv4 or IPv6 address

The address is one number: it has a hex form (each pair of hex digits is one octet), and adding 1 gives the next address. The last three lines are the interesting ones. The C library's inet_aton (which Python's socket module calls) reads 010 as octal (8), accepts the short form 127.1 (filling in the zeros) and accepts hex digits. The ipaddress module refuses all three.

Read it yourself

Here is _parse_octet, which reads each part. Read it and answer: why does it refuse 010 instead of simply reading it as ten, and why does the comment mention a security bug?

Python
    def _parse_octet(cls, octet_str):
        """Convert a decimal octet into an integer.

        Args:
            octet_str: A string, the number to parse.

        Returns:
            The octet as an integer.

        Raises:
            ValueError: if the octet isn't strictly a decimal from [0..255].

        """
        if not octet_str:
            raise ValueError("Empty octet not permitted")
        # Reject non-ASCII digits.
        if not (octet_str.isascii() and octet_str.isdigit()):
            msg = "Only decimal digits permitted in %r"
            raise ValueError(msg % octet_str)
        # We do the length check second, since the invalid character error
        # is likely to be more informative for the user
        if len(octet_str) > 3:
            msg = "At most 3 characters permitted in %r"
            raise ValueError(msg % octet_str)
        # Handle leading zeros as strict as glibc's inet_pton()
        # See security bug bpo-36384
        if octet_str != '0' and octet_str[0] == '0':
            msg = "Leading zeros are not permitted in %r"
            raise ValueError(msg % octet_str)
        # Convert to integer (we know digits are legal)
        octet_int = int(octet_str, 10)
        if octet_int > 255:
            raise ValueError("Octet %d (> 255) not permitted" % octet_int)
        return octet_int

Debugging drills

D1. The allowlist that let the wrong host through

A service accepts webhook URLs only if their host is on an allowlist, checked by a Python validator that reads each part of an IPv4 address with int(part). Requests are then sent by a component that uses the C library. An attacker registers http://010.0.0.1/ while 10.0.0.1 is allowed.

What happens, and what are the two possible fixes?

D2. A total that's a thousand times too small

A JavaScript page sums amounts from a table where large values are shown with thousands separators:

JavaScript
console.log(["1,000", "999", "10,000"].map((s) => parseFloat(s)));
Text
[ 1, 999, 10 ]

Explain the result and fix it. What other checks belong here?

D3. Order 9 comes after order 100

An admin screen sorts orders by ID, and IDs are strings in the data:

JavaScript
console.log(["9", "10", "100", "2"].sort(), ["9", "10", "100", "2"].sort((a, b) => a - b));
Text
[ '10', '100', '2', '9' ] [ '2', '9', '10', '100' ]

Why does the first sort put 10 and 100 before 2? Is the second sort the right fix?

D4. "The bits are wrong" for a negative number

A developer debugging a sensor protocol prints the byte for −5 and expects eight bits:

Python
print(format(-5, "b"), format(-5 & 0xFF, "08b"), bin(-5), (-5).to_bytes(1, "big", signed=True).hex())
print(int("11111011", 2), int.from_bytes(bytes([0b11111011]), "big", signed=True))
Text
-101 11111011 -0b101 fb
251 -5

Explain each output, and say which line shows what the sensor actually sends.

Career-oriented

Interview prep

Mid level

Q1. Convert 0xC0A8010A to dotted-decimal IP notation in your head, and explain the method.

How to get there. Split into bytes (two hex digits each), convert each byte, join with dots. Say why two hex digits are a byte.

Q2. Why do Unix file permissions use octal, and what does chmod 640 grant?

How to get there. Three yes/no bits per class of user, and 8=23.

Senior level

Q1. A service exposes sequential numeric IDs in URLs. Product wants shorter URLs. What do you propose, and what are the trade-offs?

How to get there. Length versus base, readability, guessability, and keeping the ID itself unchanged.

Q2. Your team's CSV export is opened in Excel by users in India, Germany and the US. Amounts look wrong for some of them. What's happening, and what's your fix?

How to get there. Locale conventions for decimal and grouping separators, and how a spreadsheet guesses.

Staff level

Q1. An incident review finds that one component accepted 010.0.0.1 as 10.0.0.1 and another connected to 8.0.0.1. What systemic changes do you drive?

How to get there. This is a class of bug (parser differentials), not one bug.

Q2. You're choosing the identifier format for a new platform that will run for twenty years across many teams. What do you decide, and why?

How to get there. Uniqueness, ordering, size, readability, generation without coordination, and what the format promises.