← Computing foundations · Chapter 3

Why the same bytes can be read as different values

Separate bytes, text, and types; check UTF-8, byte order, numeric precision, and whole-value regex matching at runtime boundaries.

After this guide, you can

Define encoding, ID, and numeric conversion rules and reject invalid types and ranges.

An incoming value may be bytes, text, or an already parsed object. Every conversion depends on a contract: encoding, format, field types, and error handling.

A product ID such as ITEM-042 must match its entire pattern. Finding it inside a longer string is insufficient. Likewise, the text 0.1 is not automatically a suitable settlement amount without a unit and precision policy.

Bytes require an interpretation

A byte consists of eight bits. The same bytes can represent an integer, part of a text encoding, image data, or a protocol field. Format specifications and metadata supply the interpretation that the bytes alone may not establish.

UTF-8 encodes Unicode code points using varying numbers of bytes. The character “学” uses three UTF-8 bytes, while its Python string contains one code point. Byte count, code-point count, and the number of visible characters are not interchangeable.

A visible character can combine several code points, such as a base letter and a combining mark. Some emoji also contain multiple code points. Interface truncation may need grapheme-cluster handling; transport limits follow their specified byte or token units. One string-length measurement cannot serve all these purposes.

Numeric representations have boundaries

The bytes 01 02 represent 258 in big-endian order and 513 in little-endian order. Protocols, file formats, and fields must specify byte order and width. Signed interpretation also needs a representation such as two's complement.

Numeric text and binary numbers are different types. A string "12" does not automatically satisfy an integer contract. Check ranges after parsing. Leading zeros in identifiers may matter, so converting an ID to an integer and back can change its meaning.

Many decimal fractions cannot be represented exactly by finite binary floating-point numbers. Money can use integers in explicitly defined currency minor units or an appropriate decimal representation. Specify rounding, currency scale, and calculation limits. Multiplying every amount by 100 is not a universal currency or precision rule.

Static checking and input validation have different jobs

TypeScript checks type relationships during compilation. Those types generally do not remain as runtime validators. Asserting that a response has an interface changes the type checker's view without making the response satisfy that shape.

Receive network data as untrusted input and narrow it through runtime checks. Required fields, types, lengths, and numeric ranges each need validation. Valid JSON syntax does not establish business validity.

In Python, bool is a subclass of int. An isinstance(value, int) check accepts Boolean values. Decide whether the contract permits this rather than assuming a successful type check matches the intended meaning.

Use regular expressions with explicit matching rules

Regex suits constrained text patterns, such as a fixed prefix followed by three ASCII digits. Whole-value validation requires whole-match semantics. Finding a substring is a different task. Engines differ in anchoring, escaping, Unicode categories, and performance behavior.

Python raw strings reduce escaping at the language-string layer; regex escaping still applies. The example uses [0-9] to request ASCII digits. A broader digit category may accept other characters, so that change needs a deliberate decision.

A complicated regex should not replace every parser. Nested structures, valid calendar dates, and cross-field conditions usually need suitable parsers and business checks. Bound input lengths and inspect problematic cases for expressions that can backtrack heavily.

Compare interpretations of the same data

The example checks UTF-8 length, byte order, and full ID matching. It uses synthetic bytes and performs no file or network operations.

import re
raw = "学".encode("utf-8")
assert len(raw) == 3 and len(raw.decode("utf-8")) == 1
assert int.from_bytes(b"\x01\x02", "big") == 258
assert int.from_bytes(b"\x01\x02", "little") == 513
assert re.fullmatch(r"ITEM-[0-9]{3}", "ITEM-042")
assert re.fullmatch(r"ITEM-[0-9]{3}", "xITEM-042") is None
print(len(raw), int.from_bytes(b"\x01\x02", "big"))

The output is 3 258. Adding a prefix makes the ID fail validation because the match concerns the whole input. This does not check whether a real product exists or whether the current user may access it. Those are separate business and authorization requirements.

Define decoding-error behavior too. A search preview might tolerate replacement characters, while silently replacing bytes in identifiers or signed material can destroy information. Reject, preserve the original bytes, or show an explicit error according to the use case. Do not uniformly ignore decoding failures just to make a page look normal.

Preserve meaning at boundaries

For each interface, document the raw form, parsing rule, target type, range, unit, and error response. Amounts need currency and precision; timestamps need timezone and format; IDs need case and normalization rules. Both sides should follow the same contract.

Unicode normalization can reconcile some equivalent representations, but it is not appropriate for every identifier. Normalization, whitespace trimming, and case conversion are semantic choices. Define any transformation explicitly rather than letting different modules silently apply different rules.

Exercise: validate a product record

Design a validator receiving JSON as bytes. Accept only UTF-8, a complete product ID, a nonnegative integer minor-unit amount, and a supported currency. Decode, parse, validate fields, and then apply business and permission checks.

Test invalid UTF-8, missing fields, string or Boolean amounts, extra ID prefixes, excessive amounts, and unknown currencies. Each failure should have a stable category. Keep useful diagnostic metadata without logging actual account or payment information.

Sources & further reading

Sources checked on 2026-11-10. Original engineering explanation; examples are teaching data, not production measurements.