Gray code decoder
Paste a Gray code reading and get the number it stands for: 0111 decodes to binary 0101, which is 5. Leading zeros stay in place, so fixed-width encoder readings and digital logic homework are easy to compare. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Text
- 0111
- Gray code
- 0111
- Binary
- 0101
- Integer
- 5
A Gray code decoder turns a binary-reflected Gray code word into the ordinary non-negative integer it represents. This tool accepts a bit string made only from zeroes and ones, reconstructs its standard binary form, and returns the exact integer together with both bit strings for easy checking. It is useful when reading rotary encoder positions, validating digital logic exercises, testing firmware tables, or studying how single-bit Gray transitions map back to normal counting.
What a Gray code decoder calculates
Binary-reflected Gray code labels consecutive non-negative integers so that adjacent values differ in exactly one bit. That single-bit transition is valuable in devices where several electrical signals cannot be guaranteed to change at precisely the same instant. A Gray word is not interpreted with ordinary binary place values directly.
To decode it, the most significant binary bit is copied from the most significant Gray bit. Every later binary bit is the exclusive OR of the previous decoded binary bit and the current Gray bit. In equivalent terms, each binary position is the parity of the Gray prefix ending at that position.
This capability performs that cumulative XOR from left to right, builds the corresponding standard binary string, and then evaluates that binary string as a non-negative integer. For example, Gray code 0111 becomes ordinary binary 0101 and therefore integer 5. Leading zeroes are retained in the returned Gray and binary strings, which makes fixed-width hardware readings and classroom work easier to compare, while the integer naturally has no width or leading-zero distinction.
The implementation covers binary-reflected Gray code, the common variant meant by Gray code in encoder and digital-logic contexts.
Valid input and exact output
Send the Gray word in the text field as a non-empty string containing only the characters 0 and 1. Whitespace, separators, a 0b prefix, decimal digits other than one, signs, and explanatory text are deliberately not accepted. Strict validation prevents an accidental character from silently changing a hardware position or making an answer appear correct after partial parsing.
The current exact-integer contract accepts up to 53 bits. Gray code 0 returns binary 0 and integer 0, while Gray code 1 returns binary 1 and integer 1. Identical inputs always produce identical objects because the decoder does not use the network, random values, stored state, or the system clock.
Using the decoder in hardware, education, and tests
Use the browser form when you need to inspect a Gray reading quickly, demonstrate cumulative XOR in a lesson, or check a hand calculation without writing a temporary program. For rotary and linear encoders, keep the original fixed-width reading and compare the returned binary field with the bit ordering documented by the device, since this capability assumes the submitted string is most-significant-bit first. Boundary cases worth including are all zeroes, a single one, leading zeroes, the largest intended device reading, and malformed strings containing spaces or other digits.
The decoder does not repair reversed wiring, infer bit order, remove prefixes, or guess whether a string is Gray rather than ordinary binary; those decisions belong at the input boundary.
What you can do with it
Decode an encoder position
Convert a fixed-width Gray reading from a rotary or linear encoder into the ordinary non-negative position used by application logic.
Check digital logic exercises
Show the reconstructed binary word and integer so students can verify every stage of a cumulative XOR decoding calculation.
FAQ
What kind of Gray code does this decode?
It decodes standard binary-reflected Gray code, using cumulative XOR from the most significant bit to the least significant bit.
What input is accepted?
Spaces, prefixes, signs, and other digits are invalid.
Why is the input limited to 53 bits?
Wider input can decode beyond the safe integer range, so it is rejected instead of being silently rounded.
How do I convert Gray code to binary by hand?
Copy the first bit as it is. For each next bit, compare the Gray bit with the binary bit you just wrote: write 1 if they differ and 0 if they match. That turns 0111 into 0101.
Why do rotary encoders use Gray code?
Neighboring positions differ in exactly one bit, which matters in devices where several electrical signals cannot be guaranteed to change at precisely the same instant. Decoding turns each reading back into a normal position count.
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/numth/gray-code-decode \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"text":"0111"}'const res = await fetch("https://api.kit.forhosting.com/numth/gray-code-decode", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"text": "0111"
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/numth/gray-code-decode",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"text": "0111"
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/numth/gray-code-decode", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"text":"0111"}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"text":"0111"}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/numth/gray-code-decode", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"text": "0111"
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "numth.gray_code_decode",
"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.
Limits
max_chars | 53 |
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
Invalid characters are rejected clearly instead of being ignored or partially parsed, and every valid request is handled by the same deterministic algorithm in the browser and API.
Valid input and exact output
The gray, gray_code, and bits aliases are also accepted for clients that already use one of those field names. JavaScript and JSON numbers can exactly represent integers only through their safe-integer range, so a decoded result beyond that range is rejected rather than rounded. A successful response contains gray_code, preserving the submitted width; binary, containing the reconstructed ordinary binary word; and integer, containing the decoded non-negative JSON number. Invalid input produces an invalid_input error and no misleading partial result.
Using the decoder in hardware, education, and tests
Use the API when firmware tooling, a test bench, an educational platform, or a data-import service needs the same stable operation repeatedly. Each successful API item costs $0.002; browser execution is available for interactive checks. For automated tests, assert all three response fields when width matters, or assert integer alone when only the decoded position matters.
Integration use cases
Build deterministic test fixtures
Generate stable Gray-to-integer results for firmware tables, simulators, device parsers, and continuous-integration assertions.
Technical questions
Are leading zeroes preserved?
Yes. The gray_code and binary response fields preserve the submitted bit width, while integer returns the corresponding numeric value.
How much does the API cost?
Each successful API item costs $0.002. Interactive browser execution is available for quick checks.