Fibonacci coding (Zeckendorf)
Write any positive whole number as a Fibonacci code: 6 is 5 + 1, so it becomes 10011, and every code ends in 11 so it can be spotted in a stream without a length marker. Decoding works the other way round. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Value
- 6
- Calculation mode
- Encode
- Input
- 6
- Code
- 10011
- Bits
- 10011
- Length
- 5
Fibonacci coding, also called Zeckendorf coding, writes every positive integer as a unique sum of non-consecutive Fibonacci numbers and packs that sum into a short self-delimited bit string that always ends with the terminator 11. Students meeting universal codes for the first time, instructors building exam oracles, and engineers comparing Elias gamma, Golomb, and Fibonacci codes all need the same deterministic map both ways: integer to bits and bits back to integer, with honest failure when the input is zero, negative, non-binary, or not a canonical Zeckendorf layout.
What Zeckendorf representation and Fibonacci coding mean
Zeckendorf's theorem states that every positive integer has a unique representation as a sum of Fibonacci numbers where no two summands are consecutive in the Fibonacci sequence. The usual coding convention starts the usable sequence at F2 equals 1, F3 equals 2, F4 equals 3, F5 equals 5, and so on, deliberately skipping the duplicate F1 equals 1 so uniqueness is unambiguous. To encode n you greedily pick the largest Fibonacci number not exceeding the remaining value, then skip the next lower neighbor, and repeat until the remainder is zero.
The Fibonacci code is then the bit mask of those terms from F2 up through the largest used term, written from low index to high, plus one extra terminating 1. Classic small values fix the mental model: 1 encodes as 11, 2 as 011, 3 as 0011, 4 as 1011, 5 as 00011, and 6 as 10011.
Where Fibonacci coding earns its keep in practice
Classroom and MOOC platforms use a Fibonacci coding calculator so learners can check Zeckendorf homework without hand-walking long Fibonacci tables and without confusing the code with the separate math.fibonacci nth-term tools. Competitive programming and information-theory courses need a bidirectional oracle that both produces the codeword and rejects illegal bit strings, matching contest checkers that mark wrong any non-canonical or consecutive-term encoding. Data-quality jobs can store compact self-delimited integer prefixes and verify them later by decoding and re-encoding.
In every workflow treat a valid code as well-formed integer packaging only, not as authentication or secrecy: Fibonacci coding is a transparent universal code, not encryption. Keep values inside the safe integer range for this tier-A worker, pin expected code strings in tests, and you get deterministic encode and decode for teaching, grading, and lightweight tooling without standing up a computer-algebra stack of your own.
What you can do with it
Universal-code demos and notebooks
Compare Fibonacci code lengths with Elias or unary prefixes for the same positive integers in teaching notebooks without reimplementing the greedy walk each time.
Self-delimited integer prefixes
Encode small positive IDs as Fibonacci bit strings that end with 11, then decode and re-encode in pipelines to ensure stored prefixes stay canonical.
FAQ
How do I encode a number with Fibonacci coding?
Set mode to encode and value to a positive integer.
How do I decode a Fibonacci code?
Set mode to decode and value to a 0/1 bit string ending with 11.
Why must codes end with 11?
Fibonacci codes append a terminator 1 after the Zeckendorf bit mask; the highest used term is always a 1, so every valid codeword ends with 11 and is self-delimited in a bit stream.
Why can't zero be encoded with Fibonacci coding?
Zeckendorf's rule covers positive integers only: zero has no sum of Fibonacci numbers to write down. Zero and negative numbers are therefore rejected with a clear message instead of producing a made-up code.
Why is a code with two 1 bits in a row before the end rejected?
Two 1 bits side by side mean two consecutive Fibonacci numbers, which the Zeckendorf form never uses. Such a string is not the one valid code for its number, so decoding refuses it instead of guessing.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/enc/fibonacci-coding \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"mode":"encode","value":"6"}'const res = await fetch("https://api.kit.forhosting.com/enc/fibonacci-coding", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"mode": "encode",
"value": "6"
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/enc/fibonacci-coding",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"mode": "encode",
"value": "6"
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/enc/fibonacci-coding", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"mode":"encode","value":"6"}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"mode":"encode","value":"6"}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/enc/fibonacci-coding", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"mode": "encode",
"value": "6"
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "enc.fibonacci_coding",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
This capability implements that standard F2=1, F3=2, F4=3 walk as pure parse logic shared by the free browser tool and the KIT API, so homework checks, LMS plugins, and production pipelines never disagree on a codeword. Successful API calls use prepaid balance at the published $0.002 base price; invalid input is not billed.
What Zeckendorf representation and Fibonacci coding mean
Because the highest used term always contributes a final payload 1, every valid code ends with the two-bit pattern 11, which makes the code self-delimited in a stream without a separate length field. Decoding reverses the walk: strip the trailing terminator bit, sum F2, F3, … where the payload bits are 1, and optionally re-encode to prove the bit string was the canonical Zeckendorf layout rather than an alternate sum that uses consecutive Fibonacci numbers. That uniqueness is exactly why Fibonacci coding is popular in teaching universal codes and in designs that need variable-length integer prefixes without a dictionary.
Input contract, response shape, and validation errors
Example: mode encode and value 6 yields code 10011 with zeckendorf 5 plus 1. Mode decode and value 10011 yields value 6 with the same decomposition. POST JSON with two required fields. Mode must be encode or decode (aliases op, action, and direction are accepted). Value for encode is a positive integer as a JSON number or a pure digit string within the JavaScript safe integer range up to 9007199254740991; zero, negatives, fractions, leading zeros on multi-digit strings, and non-numeric text fail with invalid_input naming what went wrong. Value for decode is a bit string of characters 0 and 1 that ends with 11; optional spaces or underscores are stripped, but any other character, an empty string, a code that is too long, a payload with consecutive 1-bits, or a layout that is not the canonical re-encoding of its decoded integer is rejected. On success both modes return mode, the echoed input, value as the integer, code and bits as the Fibonacci bit string, length, zeckendorf as the Fibonacci summands high to low, zeckendorf_sum as a display string such as 5+1, fibonacci_indices as the F-index of each summand, algorithm set to fibonacci_coding, and representation set to Zeckendorf. Failed validation does not consume prepaid balance.
Where Fibonacci coding earns its keep in practice
Compression and codec sketches often compare Fibonacci codes against Elias gamma and unary for small positive integers; having a tiny API that returns length and summands makes notebook experiments and blog demos reproducible.
Integration use cases
Homework and exam Zeckendorf checks
Students submit an integer or a candidate bit string; the API returns the canonical Fibonacci code and Fibonacci summands, or invalid_input when consecutive 1-bits break Zeckendorf rules.
Technical questions
What inputs are rejected?
Zero, negatives, non-integers, non-binary decode strings, codes that lack the 11 terminator, payloads with consecutive 1-bits, and non-canonical layouts all fail with invalid_input and are not billed.
What does Fibonacci Zeckendorf coding cost?
The browser tool is free. API requests use prepaid KIT balance at $0.002 per successful call; invalid input does not consume balance.