vix.ing · top · new · best · stats · spec

Variable-length Gray codes for the Natural Numbers

2026/07/17 by Ezequiel López-Rubio
Computer Science · Mathematics · #cs.IT #math.IT

paper · pdf

Abstract

The modular b-ary Gray code arranges fixed-length b-ary representations of intervals of natural numbers so that consecutive numbers differ in a single digit. Its usefulness, however, is tied to a fixed word length. We introduce, for every integer base b≥ 2, a variable-length Gray code Vb: a bijection from the natural numbers onto the set of all finite strings over the b-symbol alphabet \0,1,…,b-1\. The construction orders the natural numbers by codeword length into blocks and lists each block along the modular b-ary Gray code of the within-block offset, with its leading digit incremented modulo b. We prove four properties for arbitrary b. First, Vb is a bijection, a complete code that assigns exactly one codeword to every finite string over the alphabet, including the empty string. Second, the Levenshtein (edit) distance between the codewords of two consecutive integers is always one. Third, codeword length is monotone non-decreasing in the encoded number. Fourth, the transition to codewords of length k occurs exactly at n=Nk=∑i=0k-1bi, where Vb(n)=1 0k-1. The presented code, therefore, realizes a Hamiltonian enumeration under unit edit steps while retaining a near-optimal, self-adapting length profile. These properties suggest a use in machine learning: large language models routinely emit natural numbers as symbol strings, yet the positional notations they rely on are neither complete -- strings with leading zeros are invalid or redundant -- nor locally stable, since incrementing a number may rewrite many symbols at once. Because Vb is a complete code and moves by a single edit between consecutive integers, it removes both obstacles and is a natural candidate representation for numeric tokens; we develop this argument and discuss the code's compression behavior relative to fixed-length Gray codes.

Related