Fibonacci coding: compact by construction
A small algorithm file on universal integer coding, representation choices, and the value of keeping primitives testable.
- problem
- Compact integer encodings become protocol risks when representation, framing, and malformed-input behavior remain implicit.
- scope
- A compact reference to Fibonacci coding for positive integers and the representation contract around a decodable bitstream.
- environment
- Bit-oriented codecs and protocol primitives that need self-delimiting positive-integer representations.
Assumptions
- Inputs are positive integers.
- Encoder and decoder share the same Fibonacci basis and terminator rule.
Limitations
- No production implementation, performance comparison, or malformed-stream test corpus is published here.
Table of contents 3 sections
Define the representation contract
Fibonacci coding represents positive integers as sums of non-consecutive Fibonacci numbers and uses a terminator to make the stream decodable. The mechanism is compact; the representation contract is the real subject.
The encoder derives the Zeckendorf representation: a unique sum of non-consecutive Fibonacci numbers. Bits mark the selected basis values, and an additional terminal one produces the only adjacent-one pair in a valid codeword. The decoder can therefore stream until it sees 11. That elegant delimiter still needs explicit bit order, integer domain, basis indexing, overflow behavior, and concatenation rules.
Keep the primitive testable
Small primitives deserve the same discipline as large systems: a precise problem statement, an implementation sketch, known test vectors, and failure cases that fit on one screen.
Property tests should round-trip a dense prefix of positive integers and a randomized high range. Boundary tests cover one, consecutive basis transitions, the largest representable value, truncated streams, an unterminated word, impossible internal 11 pairs, and arithmetic overflow while accumulating the result. A reference implementation can prioritize transparency while a production variant proves the same vectors under optimized bit I/O.
Treat compression as protocol
Compression details look minor until they become protocol. Then ambiguity, framing, and malformed input are architecture.
The universal code is prefix-free, not magically self-authenticating. A corrupted bit can change one integer and resynchronize later, or it can shift the semantic structure expected by the surrounding protocol. The container still needs length budgets, count limits, integrity protection where required, and a decoder that rejects resource-exhaustion inputs before allocation. Compactness never removes the need for an adversarial parser.
- sourced Fibonacci coding definition
The universal code uses Zeckendorf representation plus a terminal one bit to produce a prefix-free stream.
inspect source ↗
- reference Fibonacci coding referenceopen ↗
External overview of the representation and decoding rule.