The reflected binary code (RBC), also known as reflected binary (RB) or Gray code after
Frank Gray
Francis Tierney Gray (born 27 October 1954) is a Scottish football manager and former player. He played for Leeds United, Nottingham Forest, Sunderland and Darlington, while he also represented Scotland 32 times.
Gray has managed Darlington, ...
, is an ordering of the
binary numeral system such that two successive values differ in only one
bit
The bit is the most basic unit of information in computing and digital communications. The name is a portmanteau of binary digit. The bit represents a logical state with one of two possible values. These values are most commonly represente ...
(binary digit).
For example, the representation of the decimal value "1" in binary would normally be "" and "2" would be "". In Gray code, these values are represented as "" and "". That way, incrementing a value from 1 to 2 requires only one bit to change, instead of two.
Gray codes are widely used to prevent spurious output from
electromechanical
In engineering, electromechanics combines processes and procedures drawn from electrical engineering and mechanical engineering. Electromechanics focuses on the interaction of electrical and mechanical systems as a whole and how the two systems ...
switch
In electrical engineering, a switch is an electrical component that can disconnect or connect the conducting path in an electrical circuit, interrupting the electric current or diverting it from one conductor to another. The most common type of ...
es and to facilitate
error correction in digital communications such as
digital terrestrial television
Digital terrestrial television (DTTV or DTT, or DTTB with "broadcasting") is a technology for terrestrial television in which land-based (terrestrial) television stations broadcast television content by radio waves to televisions in consumers' ...
and some
cable TV systems.
Motivation and name
Many devices indicate position by closing and opening switches. If that device uses
natural binary codes, positions 3 and 4 are next to each other but all three bits of the binary representation differ:
:
The problem with natural binary codes is that physical switches are not ideal: it is very unlikely that physical switches will change states exactly in synchrony. In the transition between the two states shown above, all three switches change state. In the brief period while all are changing, the switches will read some spurious position. Even without
keybounce
In electrical engineering, a switch is an electrical component that can disconnect or connect the conducting path in an electrical circuit, interrupting the electric current or diverting it from one conductor to another. The most common type of ...
, the transition might look like — — — . When the switches appear to be in position , the observer cannot tell if that is the "real" position 1, or a transitional state between two other positions. If the output feeds into a
sequential
In mathematics, a sequence is an enumerated collection of objects in which repetitions are allowed and order matters. Like a set, it contains members (also called ''elements'', or ''terms''). The number of elements (possibly infinite) is called th ...
system, possibly via
combinational logic
In automata theory, combinational logic (also referred to as time-independent logic or combinatorial logic) is a type of digital logic which is implemented by Boolean circuits, where the output is a pure function of the present input only. This ...
, then the sequential system may store a false value.
This problem can be solved by changing only one switch at a time, so there is never any ambiguity of position, resulting in codes assigning to each of a contiguous set of
integer
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the languag ...
s, or to each member of a circular list, a word of symbols such that no two code words are identical and each two adjacent code words differ by exactly one symbol. These codes are also known as ''unit-distance'',
''single-distance'', ''single-step'', ''monostrophic''
or ''syncopic codes'',
in reference to the
Hamming distance
In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. In other words, it measures the minimum number of ''substitutions'' required to chan ...
of 1 between adjacent codes.
In principle, there can be more than one such code for a given word length, but the term Gray code was first applied to a particular
binary
Binary may refer to:
Science and technology Mathematics
* Binary number, a representation of numbers using only two digits (0 and 1)
* Binary function, a function that takes two arguments
* Binary operation, a mathematical operation that ta ...
code for non-negative integers, the ''binary-reflected Gray code'', or BRGC.
Bell Labs
Nokia Bell Labs, originally named Bell Telephone Laboratories (1925–1984),
then AT&T Bell Laboratories (1984–1996)
and Bell Labs Innovations (1996–2007),
is an American industrial Research and development, research and scientific developm ...
researcher
George R. Stibitz described such a code in a 1941 patent application, granted in 1943.
Frank Gray
Francis Tierney Gray (born 27 October 1954) is a Scottish football manager and former player. He played for Leeds United, Nottingham Forest, Sunderland and Darlington, while he also represented Scotland 32 times.
Gray has managed Darlington, ...
introduced the term ''reflected binary code'' in his 1947 patent application, remarking that the code had "as yet no recognized name".
He derived the name from the fact that it "may be built up from the conventional binary code by a sort of reflection process".
In the standard encoding the least significant bit follows a repetitive pattern of 2 on, 2 off the next digit a pattern of 4 on, 4 off; the ''n''th least significant bit a pattern of 2
''n'' on 2
''n'' off. The four-bit version of this is shown below:
:
For decimal 15 the code rolls over to decimal 0 with only one switch change. This is called the cyclic or adjacency property of the code.
In modern
digital communications
Data transmission and data reception or, more broadly, data communication or digital communications is the transfer and reception of data in the form of a digital bitstream or a digitized analog signal transmitted over a point-to-point or ...
, Gray codes play an important role in
error correction. For example, in a
digital modulation
In electronics and telecommunications, modulation is the process of varying one or more properties of a periodic waveform, called the ''carrier signal'', with a separate signal called the ''modulation signal'' that typically contains informatio ...
scheme such as
QAM
Quadrature amplitude modulation (QAM) is the name of a family of digital modulation methods and a related family of analog modulation methods widely used in modern telecommunications to transmit information. It conveys two analog message signa ...
where data is typically transmitted in
symbols of 4 bits or more, the signal's
constellation diagram
A constellation diagram is a representation of a signal modulated by a digital modulation scheme such as quadrature amplitude modulation or phase-shift keying. It displays the signal as a two-dimensional ''xy''-plane scatter diagram in the ...
is arranged so that the bit patterns conveyed by adjacent constellation points differ by only one bit. By combining this with
forward error correction capable of correcting single-bit errors, it is possible for a receiver to correct any transmission errors that cause a constellation point to deviate into the area of an adjacent point. This makes the transmission system less susceptible to
noise
Noise is unwanted sound considered unpleasant, loud or disruptive to hearing. From a physics standpoint, there is no distinction between noise and desired sound, as both are vibrations through a medium, such as air or water. The difference aris ...
.
Despite the fact that Stibitz described this code
before Gray, the reflected binary code was later named after Gray by others who used it. Two different 1953 patent applications use "Gray code" as an alternative name for the "reflected binary code";
one of those also lists "minimum error code" and "cyclic permutation code" among the names.
A 1954 patent application refers to "the Bell Telephone Gray code".
Other names include "cyclic binary code",
"cyclic progression code",
"cyclic permuting binary"
or "cyclic permuted binary" (CPB).
The Gray code was sometimes attributed, incorrectly,
to
Elisha Gray.
History and practical application
Mathematical puzzles
Reflected binary codes were applied to mathematical puzzles before they became known to engineers.
The binary-reflected Gray code represents the underlying scheme of the classical
Chinese rings puzzle
Baguenaudier (; French for "time-waster"), also known as the Chinese rings, Cardan's suspension, Cardano's rings, Devil's needle or five pillars puzzle, is a disentanglement puzzle featuring a loop which must be disentangled from a sequence of ...
, a sequential mechanical puzzle mechanism described by the French Louis Gros in 1872.
It can serve as a solution guide for the
Towers of Hanoi
The Tower of Hanoi (also called The problem of Benares Temple or Tower of Brahma or Lucas' Tower and sometimes pluralized as Towers, or simply pyramid puzzle) is a mathematical game or puzzle consisting of three rods and a number of disks of v ...
problem, based on a game by the French
Édouard Lucas
__NOTOC__
François Édouard Anatole Lucas (; 4 April 1842 – 3 October 1891) was a French mathematician. Lucas is known for his study of the Fibonacci sequence. The related Lucas sequences and Lucas numbers are named after him.
Biography
Lucas ...
in 1883.
Similarly, the so-called Towers of Bucharest and Towers of Klagenfurt game configurations yield
ternary and pentary Gray codes.
Martin Gardner
Martin Gardner (October 21, 1914May 22, 2010) was an American popular mathematics and popular science writer with interests also encompassing scientific skepticism, micromagic, philosophy, religion, and literatureespecially the writings of Lew ...
wrote a popular account of the Gray code in his August 1972
Mathematical Games column
Over a period of 24 years (January 1957 – December 1980), Martin Gardner wrote 288 consecutive monthly "Mathematical Games" columns for ''Scientific American'' magazine. During the next years, through June 1986, Gardner wrote 9 more columns, ...
in
Scientific American
''Scientific American'', informally abbreviated ''SciAm'' or sometimes ''SA'', is an American popular science magazine. Many famous scientists, including Albert Einstein and Nikola Tesla, have contributed articles to it. In print since 1845, it ...
.
The code also forms a
Hamiltonian cycle
In the mathematical field of graph theory, a Hamiltonian path (or traceable path) is a path in an undirected or directed graph that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a cycle that visits each vertex ...
on a
hypercube, where each bit is seen as one dimension.
Telegraphy codes
When the French engineer
Émile Baudot
Jean-Maurice-Émile Baudot (; 11 September 1845 – 28 March 1903), French telegraph engineer and inventor of the first means of digital communication Baudot code, was one of the pioneers of telecommunications. He invented a multiplexed printi ...
changed from using a 6-unit (6-bit) code to 5-unit code for his
printing telegraph
The printing telegraph was invented by Royal Earl House in 1846. House's equipment could transmit around 40 instantly readable words per minute, but was difficult to manufacture in bulk. The printer could copy and print out up to 2,000 words per ...
system, in 1875
or 1876,
he ordered the alphabetic characters on his print wheel using a reflected binary code, and assigned the codes using only three of the bits to vowels. With vowels and consonants sorted in their alphabetical order,
and other symbols appropriately placed, the 5-bit character code has been recognized as a reflected binary code.
This code became known as
Baudot code
The Baudot code is an early character encoding for telegraphy invented by Émile Baudot in the 1870s. It was the predecessor to the International Telegraph Alphabet No. 2 (ITA2), the most common teleprinter code in use until the advent of ASCII ...
and, with minor changes, was eventually adopted as
International Telegraph Alphabet No. 1 (ITA1, CCITT-1) in 1932.
About the same time, the German-Austrian
demonstrated another printing telegraph in Vienna using a 5-bit reflected binary code for the same purpose, in 1874.
Analog-to-digital signal conversion
Frank Gray
Francis Tierney Gray (born 27 October 1954) is a Scottish football manager and former player. He played for Leeds United, Nottingham Forest, Sunderland and Darlington, while he also represented Scotland 32 times.
Gray has managed Darlington, ...
, who became famous for inventing the signaling method that came to be used for compatible color television, invented a method to convert analog signals to reflected binary code groups using
vacuum tube
A vacuum tube, electron tube, valve (British usage), or tube (North America), is a device that controls electric current flow in a high vacuum between electrodes to which an electric potential difference has been applied.
The type known as ...
-based apparatus. Filed in 1947, the method and apparatus were granted a patent in 1953,
and the name of Gray stuck to the codes. The "
PCM tube" apparatus that Gray patented was made by Raymond W. Sears of Bell Labs, working with Gray and William M. Goodall, who credited Gray for the idea of the reflected binary code.
Gray was most interested in using the codes to minimize errors in converting analog signals to digital; his codes are still used today for this purpose.
Position encoders
Gray codes are used in linear and rotary position encoders (
absolute encoder
A rotary encoder, also called a shaft encoder, is an electro-mechanical device that converts the angular position or motion of a shaft or axle to analog or digital output signals.
There are two main types of rotary encoder: absolute and increm ...
s and
quadrature encoder
An incremental encoder is a linear or rotary electromechanical device that has two output signals, ''A'' and ''B'', which issue pulses when the device is moved. Together, the ''A'' and ''B'' signals indicate both the occurrence of and direction o ...
s) in preference to weighted binary encoding. This avoids the possibility that, when multiple bits change in the binary representation of a position, a misread will result from some of the bits changing before others.
For example, some rotary encoders provide a disk which has an electrically conductive Gray code pattern on concentric rings (tracks). Each track has a stationary metal spring contact that provides electrical contact to the conductive code pattern. Together, these contacts produce output signals in the form of a Gray code. Other encoders employ non-contact mechanisms based on optical or magnetic sensors to produce the Gray code output signals.
Regardless of the mechanism or precision of a moving encoder, position measurement error can occur at specific positions (at code boundaries) because the code may be changing at the exact moment it is read (sampled). A binary output code could cause significant position measurement errors because it is impossible to make all bits change at exactly the same time. If, at the moment the position is sampled, some bits have changed and others have not, the sampled position will be incorrect. In the case of absolute encoders, the indicated position may be far away from the actual position and, in the case of incremental encoders, this can corrupt position tracking.
In contrast, the Gray code used by position encoders ensures that the codes for any two consecutive positions will differ by only one bit and, consequently, only one bit can change at a time. In this case, the maximum position error will be small, indicating a position adjacent to the actual position.
Genetic algorithms
Due to the
Hamming distance
In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. In other words, it measures the minimum number of ''substitutions'' required to chan ...
properties of Gray codes, they are sometimes used in
genetic algorithms.
They are very useful in this field, since mutations in the code allow for mostly incremental changes, but occasionally a single bit-change can cause a big leap and lead to new properties.
Boolean circuit minimization
Gray codes are also used in labelling the axes of
Karnaugh map
The Karnaugh map (KM or K-map) is a method of simplifying Boolean algebra expressions. Maurice Karnaugh introduced it in 1953 as a refinement of Edward W. Veitch's 1952 Veitch chart, which was a rediscovery of Allan Marquand's 1881 ''logi ...
s since 1953
as well as in
Händler circle graphs since 1958,
both graphical methods for
logic circuit minimization.
Error correction
In modern
digital communications
Data transmission and data reception or, more broadly, data communication or digital communications is the transfer and reception of data in the form of a digital bitstream or a digitized analog signal transmitted over a point-to-point or ...
, Gray codes play an important role in
error correction. For example, in a
digital modulation
In electronics and telecommunications, modulation is the process of varying one or more properties of a periodic waveform, called the ''carrier signal'', with a separate signal called the ''modulation signal'' that typically contains informatio ...
scheme such as
QAM
Quadrature amplitude modulation (QAM) is the name of a family of digital modulation methods and a related family of analog modulation methods widely used in modern telecommunications to transmit information. It conveys two analog message signa ...
where data is typically transmitted in
symbols of 4 bits or more, the signal's
constellation diagram
A constellation diagram is a representation of a signal modulated by a digital modulation scheme such as quadrature amplitude modulation or phase-shift keying. It displays the signal as a two-dimensional ''xy''-plane scatter diagram in the ...
is arranged so that the bit patterns conveyed by adjacent constellation points differ by only one bit. By combining this with
forward error correction capable of correcting single-bit errors, it is possible for a
receiver to correct any transmission errors that cause a constellation point to deviate into the area of an adjacent point. This makes the transmission system less susceptible to
noise
Noise is unwanted sound considered unpleasant, loud or disruptive to hearing. From a physics standpoint, there is no distinction between noise and desired sound, as both are vibrations through a medium, such as air or water. The difference aris ...
.
Communication between clock domains
Digital logic designers use Gray codes extensively for passing multi-bit count information between synchronous logic that operates at different clock frequencies. The logic is considered operating in different "clock domains". It is fundamental to the design of large chips that operate with many different clocking frequencies.
Cycling through states with minimal effort
If a system has to cycle through all possible combinations of on-off states of some set of controls, and the changes of the controls require non-trivial expense (e.g. time, wear, human work), a Gray code minimizes the number of setting changes to just one change for each combination of states. An example would be testing a piping system for all combinations of settings of its manually operated valves.
A
balanced Gray code can be constructed,
that flips every bit equally often. Since bit-flips are evenly distributed, this is optimal in the following way: balanced Gray codes minimize the maximal count of bit-flips for each digit.
Gray code counters and arithmetic
George R. Stibitz utilized a reflected binary code in a binary pulse counting device in 1941 already.
A typical use of Gray code counters is building a
FIFO (first-in, first-out) data buffer that has read and write ports that exist in different clock domains. The input and output counters inside such a dual-port FIFO are often stored using Gray code to prevent invalid transient states from being captured when the count crosses clock domains.
The updated read and write pointers need to be passed between clock domains when they change, to be able to track FIFO empty and full status in each domain. Each bit of the pointers is sampled non-deterministically for this clock domain transfer. So for each bit, either the old value or the new value is propagated. Therefore, if more than one bit in the multi-bit pointer is changing at the sampling point, a "wrong" binary value (neither new nor old) can be propagated. By guaranteeing only one bit can be changing, Gray codes guarantee that the only possible sampled values are the new or old multi-bit value. Typically Gray codes of power-of-two length are used.
Sometimes digital buses in electronic systems are used to convey quantities that can only increase or decrease by one at a time, for example the output of an event counter which is being passed between clock domains or to a digital-to-analog converter. The advantage of Gray codes in these applications is that differences in the propagation delays of the many wires that represent the bits of the code cannot cause the received value to go through states that are out of the Gray code sequence. This is similar to the advantage of Gray codes in the construction of mechanical encoders, however the source of the Gray code is an electronic counter in this case. The counter itself must count in Gray code, or if the counter runs in binary then the output value from the counter must be reclocked after it has been converted to Gray code, because when a value is converted from binary to Gray code,
it is possible that differences in the arrival times of the binary data bits into the binary-to-Gray conversion circuit will mean that the code could go briefly through states that are wildly out of sequence. Adding a clocked register after the circuit that converts the count value to Gray code may introduce a clock cycle of latency, so counting directly in Gray code may be advantageous.
To produce the next count value in a Gray-code counter, it is necessary to have some combinational logic that will increment the current count value that is stored. One way to increment a Gray code number is to convert it into ordinary binary code,
add one to it with a standard binary adder, and then convert the result back to Gray code.
Other methods of counting in Gray code are discussed in a report by
Robert W. Doran, including taking the output from the first latches of the master-slave flip flops in a binary ripple counter.
Gray code addressing
As the execution of
program code typically causes an instruction memory access pattern of locally consecutive addresses,
bus encoding Bus encoding refers to converting/encoding a piece of data to another form before launching on the bus. While bus encoding can be used to serve various purposes like reducing the number of pins, compressing the data to be transmitted, reducing cross ...
s using Gray code addressing instead of binary addressing can reduce the number of state changes of the address bits significantly, thereby reducing the
CPU power consumption in some low-power designs.
Constructing an ''n''-bit Gray code
The binary-reflected Gray code list for ''n'' bits can be generated
recursively
Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics ...
from the list for ''n'' − 1 bits by reflecting the list (i.e. listing the entries in reverse order), prefixing the entries in the original list with a binary , prefixing the entries in the reflected list with a binary , and then concatenating the original list with the reversed list.
For example, generating the ''n'' = 3 list from the ''n'' = 2 list:
The one-bit Gray code is ''G''
1 = (). This can be thought of as built recursively as above from a zero-bit Gray code ''G''
0 = (
Λ ) consisting of a single entry of zero length. This iterative process of generating ''G''
''n''+1 from ''G''
''n'' makes the following properties of the standard reflecting code clear:
* ''G''
''n'' is a
permutation of the numbers 0, ..., 2
''n'' − 1. (Each number appears exactly once in the list.)
* ''G''
''n'' is embedded as the first half of ''G''
''n''+1.
* Therefore, the coding is ''stable'', in the sense that once a binary number appears in ''G''
''n'' it appears in the same position in all longer lists; so it makes sense to talk about ''the'' reflective Gray code value of a number: ''G''(''m'') = the ''m''th reflecting Gray code, counting from 0.
* Each entry in ''G''
''n'' differs by only one bit from the previous entry. (The Hamming distance is 1.)
* The last entry in ''G''
''n'' differs by only one bit from the first entry. (The code is cyclic.)
These characteristics suggest a simple and fast method of translating a binary value into the corresponding Gray code. Each bit is inverted if the next higher bit of the input value is set to one. This can be performed in parallel by a bit-shift and exclusive-or operation if they are available: the ''n''th Gray code is obtained by computing
. Prepending a bit leaves the order of the code words unchanged, prepending a bit reverses the order of the code words. If the bits at position
of codewords are inverted, the order of neighbouring blocks of
codewords is reversed. For example, if bit 0 is inverted in a 3 bit codeword sequence, the order of two neighbouring codewords is reversed
: → (invert bit 0)
If bit 1 is inverted, blocks of 2 codewords change order:
: → (invert bit 1)
If bit 2 is inverted, blocks of 4 codewords reverse order:
: → (invert bit 2)
Thus, performing an
exclusive or
Exclusive or or exclusive disjunction is a logical operation that is true if and only if its arguments differ (one is true, the other is false).
It is symbolized by the prefix operator J and by the infix operators XOR ( or ), EOR, EXOR, , ...
on a bit
at position
with the bit
at position
leaves the order of codewords intact if
, and reverses the order of blocks of
codewords if
. Now, this is exactly the same operation as the reflect-and-prefix method to generate the Gray code.
A similar method can be used to perform the reverse translation, but the computation of each bit depends on the computed value of the next higher bit so it cannot be performed in parallel. Assuming
is the
th Gray-coded bit (
being the most significant bit), and
is the
th binary-coded bit (
being the most-significant bit), the reverse translation can be given recursively:
, and
. Alternatively, decoding a Gray code into a binary number can be described as a
prefix sum In computer science, the prefix sum, cumulative sum, inclusive scan, or simply scan of a sequence of numbers is a second sequence of numbers , the sums of prefixes ( running totals) of the input sequence:
:
:
:
:...
For instance, the prefix sums ...
of the bits in the Gray code, where each individual summation operation in the prefix sum is performed modulo two.
To construct the binary-reflected Gray code iteratively, at step 0 start with the
, and at step
find the bit position of the least significant in the binary representation of
and flip the bit at that position in the previous code
to get the next code
. The bit positions start 0, 1, 0, 2, 0, 1, 0, 3, ....
See
find first set
In computer software and hardware, find first set (ffs) or find first one is a bit operation that, given an unsigned machine word, designates the index or position of the least significant bit set to one in the word counting from the least signifi ...
for efficient algorithms to compute these values.
Converting to and from Gray code
The following functions in
C convert between binary numbers and their associated Gray codes. While it may seem that Gray-to-binary conversion requires each bit to be handled one at a time, faster algorithms exist.
typedef unsigned int uint;
// This function converts an unsigned binary number to reflected binary Gray code.
uint BinaryToGray(uint num)
// This function converts a reflected binary Gray code number to a binary number.
uint GrayToBinary(uint num)
// A more efficient version for Gray codes 32 bits or fewer through the use of SWAR (SIMD within a register) techniques.
// It implements a parallel prefix XOR function. The assignment statements can be in any order.
//
// This function can be adapted for longer Gray codes by adding steps.
uint GrayToBinary32(uint num)
// A Four-bit-at-once variant changes a binary number (abcd)2 to (abcd)2 ^ (00ab)2, then to (abcd)2 ^ (00ab)2 ^ (0abc)2 ^ (000a)2.
On newer processors, the number of ALU instructions in the decoding step can be reduced by taking advantage of the
CLMUL instruction set Carry-less Multiplication (CLMUL) is an extension to the x86 instruction set used by microprocessors from Intel and AMD which was proposed by Intel in March 2008 and made available in the Intel Westmere processors announced in early 2010. Mathema ...
. If MASK is the constant binary string of ones ended with a single zero digit, then carryless multiplication of MASK with the grey encoding of x will always give either x or its bitwise negation.
Special types of Gray codes
In practice, "Gray code" almost always refers to a binary-reflected Gray code (BRGC).
However, mathematicians have discovered other kinds of Gray codes.
Like BRGCs, each consists of a list of words, where each word differs from the next in only one digit (each word has a
Hamming distance
In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. In other words, it measures the minimum number of ''substitutions'' required to chan ...
of 1 from the next word).
Gray codes with ''n'' bits and of length less than
It is possible to construct binary Gray codes with ''n'' bits with a length of less than , if the length is even. One possibility is to start with a balanced Gray code and remove pairs of values at either the beginning and the end, or in the middle.
OEIS
The On-Line Encyclopedia of Integer Sequences (OEIS) is an online database of integer sequences. It was created and maintained by Neil Sloane while researching at AT&T Labs. He transferred the intellectual property and hosting of the OEIS to the ...
sequence A290772 gives the number of possible Gray sequences of length which include zero and use the minimum number of bits.
''n''-ary Gray code
There are many specialized types of Gray codes other than the binary-reflected Gray code. One such type of Gray code is the ''n''-ary Gray code, also known as a non-Boolean Gray code. As the name implies, this type of Gray code uses non-
Boolean values in its encodings.
For example, a 3-ary (
ternary) Gray code would use the values .
The (''n'', ''k'')-''Gray code'' is the ''n''-ary Gray code with ''k'' digits.
The sequence of elements in the (3, 2)-Gray code is: . The (''n'', ''k'')-Gray code may be constructed recursively, as the BRGC, or may be constructed
iteratively. An
algorithm
In mathematics and computer science, an algorithm () is a finite sequence of rigorous instructions, typically used to solve a class of specific problems or to perform a computation. Algorithms are used as specifications for performing ...
to iteratively generate the (''N'', ''k'')-Gray code is presented (in
C):
// inputs: base, digits, value
// output: Gray
// Convert a value to a Gray code with the given base and digits.
// Iterating through a sequence of values would result in a sequence
// of Gray codes in which only one digit changes at a time.
void toGray(unsigned base, unsigned digits, unsigned value, unsigned gray igits
// EXAMPLES
// input: value = 1899, base = 10, digits = 4
// output: baseN[] = [9,9,8,1], gray[] = [0,1,7,1]
// input: value = 1900, base = 10, digits = 4
// output: baseN[] = [0,0,9,1], gray[] = [0,1,8,1]
There are other Gray code algorithms for (''n'',''k'')-Gray codes. The (''n'',''k'')-Gray code produced by the above algorithm is always cyclical; some algorithms, such as that by Guan,
lack this property when k is odd. On the other hand, while only one digit at a time changes with this method, it can change by wrapping (looping from ''n'' − 1 to 0). In Guan's algorithm, the count alternately rises and falls, so that the numeric difference between two Gray code digits is always one.
Gray codes are not uniquely defined, because a permutation of the columns of such a code is a Gray code too. The above procedure produces a code in which the lower the significance of a digit, the more often it changes, making it similar to normal counting methods.
See also
Skew binary number system
Skew may refer to:
In mathematics
* Skew lines, neither parallel nor intersecting.
* Skew normal distribution, a probability distribution
* Skew field or division ring
* Skew-Hermitian matrix
* Skew lattice
* Skew polygon, whose vertices do not l ...
, a variant ternary number system where at most two digits change on each increment, as each increment can be done with at most one digit
carry
Carry or carrying may refer to:
People
*Carry (name)
Finance
* Carried interest (or carry), the share of profits in an investment fund paid to the fund manager
* Carry (investment), a financial term: the carry of an asset is the gain or cost of h ...
operation.
Balanced Gray code
Although the binary reflected Gray code is useful in many scenarios, it is not optimal in certain cases because of a lack of "uniformity".
In balanced Gray codes, the number of changes in different coordinate positions are as close as possible. To make this more precise, let ''G'' be an ''R''-ary complete Gray cycle having transition sequence
; the ''transition counts'' (''spectrum'') of ''G'' are the collection of integers defined by
:
A Gray code is ''uniform'' or ''uniformly balanced'' if its transition counts are all equal, in which case we have
for all ''k''. Clearly, when
, such codes exist only if ''n'' is a power of 2. If ''n'' is not a power of 2, it is possible to construct ''well-balanced'' binary codes where the difference between two transition counts is at most 2; so that (combining both cases) every transition count is either
or
.
Gray codes can also be ''exponentially balanced'' if all of their transition counts are adjacent powers of two, and such codes exist for every power of two.
For example, a balanced 4-bit Gray code has 16 transitions, which can be evenly distributed among all four positions (four transitions per position), making it uniformly balanced:
:
:
:
:
whereas a balanced 5-bit Gray code has a total of 32 transitions, which cannot be evenly distributed among the positions. In this example, four positions have six transitions each, and one has eight:
:
:
:
:
:
We will now show a construction
and implementation
for well-balanced binary Gray codes which allows us to generate an ''n''-digit balanced Gray code for every ''n''. The main principle is to inductively construct an (''n'' + 2)-digit Gray code
given an ''n''-digit Gray code ''G'' in such a way that the balanced property is preserved. To do this, we consider partitions of
into an even number ''L'' of non-empty blocks of the form
:
where
,
, and
). This partition induces an
-digit Gray code given by
:
:
:
:
If we define the ''transition multiplicities''
:
to be the number of times the digit in position ''i'' changes between consecutive blocks in a partition, then for the (''n'' + 2)-digit Gray code induced by this partition the transition spectrum
is
:
The delicate part of this construction is to find an adequate partitioning of a balanced ''n''-digit Gray code such that the code induced by it remains balanced, but for this only the transition multiplicities matter; joining two consecutive blocks over a digit
transition and splitting another block at another digit
transition produces a different Gray code with exactly the same transition spectrum
, so one may for example
designate the first
transitions at digit
as those that fall between two blocks. Uniform codes can be found when
and
, and this construction can be extended to the ''R''-ary case as well.
Long run Gray codes
Long run (or ''maximum gap'') Gray codes maximize the distance between consecutive changes of digits in the same position. That is, the minimum run-length of any bit remains unchanged for as long as possible.
Monotonic Gray codes
Monotonic codes are useful in the theory of interconnection networks, especially for minimizing dilation for linear arrays of processors.
If we define the ''weight'' of a binary string to be the number of 1s in the string, then although we clearly cannot have a Gray code with strictly increasing weight, we may want to approximate this by having the code run through two adjacent weights before reaching the next one.
We can formalize the concept of monotone Gray codes as follows: consider the partition of the hypercube
into ''levels'' of vertices that have equal weight, i.e.
:
for
. These levels satisfy
. Let
be the subgraph of
induced by
, and let
be the edges in
. A monotonic Gray code is then a Hamiltonian path in
such that whenever
comes before
in the path, then
.
An elegant construction of monotonic ''n''-digit Gray codes for any ''n'' is based on the idea of recursively building subpaths
of length
having edges in
.
We define
,
whenever
or
, and
:
otherwise. Here,
is a suitably defined permutation and
refers to the path ''P'' with its coordinates permuted by
. These paths give rise to two monotonic ''n''-digit Gray codes
and
given by
:
The choice of
which ensures that these codes are indeed Gray codes turns out to be
. The first few values of
are shown in the table below.
These monotonic Gray codes can be efficiently implemented in such a way that each subsequent element can be generated in ''O''(''n'') time. The algorithm is most easily described using
coroutine
Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
s.
Monotonic codes have an interesting connection to the
Lovász conjecture, which states that every connected
vertex-transitive graph
In the mathematical field of graph theory, a vertex-transitive graph is a graph in which, given any two vertices and of , there is some automorphism
:f : G \to G\
such that
:f(v_1) = v_2.\
In other words, a graph is vertex-transitive ...
contains a Hamiltonian path. The "middle-level" subgraph
is
vertex-transitive
In geometry, a polytope (e.g. a polygon or polyhedron) or a tiling is isogonal or vertex-transitive if all its vertices are equivalent under the symmetries of the figure. This implies that each vertex is surrounded by the same kinds of face in ...
(that is, its automorphism group is transitive, so that each vertex has the same "local environment" and cannot be differentiated from the others, since we can relabel the coordinates as well as the binary digits to obtain an
automorphism) and the problem of finding a Hamiltonian path in this subgraph is called the "middle-levels problem", which can provide insights into the more general conjecture. The question has been answered affirmatively for
, and the preceding construction for monotonic codes ensures a Hamiltonian path of length at least 0.839''N'' where ''N'' is the number of vertices in the middle-level subgraph.
Beckett–Gray code
Another type of Gray code, the Beckett–Gray code, is named for Irish playwright
Samuel Beckett, who was interested in
symmetry. His play "
Quad" features four actors and is divided into sixteen time periods. Each period ends with one of the four actors entering or leaving the stage. The play begins and ends with an empty stage, and Beckett wanted each subset of actors to appear on stage exactly once.
Clearly the set of actors currently on stage can be represented by a 4-bit binary Gray code. Beckett, however, placed an additional restriction on the script: he wished the actors to enter and exit so that the actor who had been on stage the longest would always be the one to exit. The actors could then be represented by a
first in, first out queue __NOTOC__
Queue () may refer to:
* Queue area, or queue, a line or area where people wait for goods or services
Arts, entertainment, and media
*''ACM Queue'', a computer magazine
* ''The Queue'' (Sorokin novel), a 1983 novel by Russian author ...
, so that (of the actors onstage) the actor being dequeued is always the one who was enqueued first.
Beckett was unable to find a Beckett–Gray code for his play, and indeed, an exhaustive listing of all possible sequences reveals that no such code exists for ''n'' = 4. It is known today that such codes do exist for ''n'' = 2, 5, 6, 7, and 8, and do not exist for ''n'' = 3 or 4. An example of an 8-bit Beckett–Gray code can be found in
Donald Knuth
Donald Ervin Knuth ( ; born January 10, 1938) is an American computer scientist, mathematician, and professor emeritus at Stanford University. He is the 1974 recipient of the ACM Turing Award, informally considered the Nobel Prize of computer sc ...
's ''Art of Computer Programming''.
According to Sawada and Wong, the search space for ''n'' = 6 can be explored in 15 hours, and more than 9,500 solutions for the case ''n'' = 7 have been found.
Snake-in-the-box codes
Snake-in-the-box
The snake-in-the-box problem in graph theory and computer science deals with finding a certain kind of path along the edges of a hypercube. This path starts at one corner and travels along the edges to as many corners as it can reach. After it g ...
codes, or ''snakes'', are the sequences of nodes of
induced path
In the mathematical area of graph theory, an induced path in an undirected graph is a path that is an induced subgraph of . That is, it is a sequence of vertices in such that each two adjacent vertices in the sequence are connected by an edg ...
s in an ''n''-dimensional
hypercube graph
In graph theory, the hypercube graph is the graph formed from the vertices and edges of an -dimensional hypercube. For instance, the cube graph is the graph formed by the 8 vertices and 12 edges of a three-dimensional cube.
has vertices, e ...
, and coil-in-the-box codes,
or ''coils'', are the sequences of nodes of induced
cycles in a hypercube. Viewed as Gray codes, these sequences have the property of being able to detect any single-bit coding error. Codes of this type were first described by
William H. Kautz in the late 1950s;
since then, there has been much research on finding the code with the largest possible number of codewords for a given hypercube dimension.
Single-track Gray code
Yet another kind of Gray code is the single-track Gray code (STGC) developed by Norman B. Spedding
and refined by Hiltgen, Paterson and Brandestini in "Single-track Gray codes" (1996).
The STGC is a cyclical list of ''P'' unique binary encodings of length n such that two consecutive words differ in exactly one position, and when the list is examined as a ''P'' × ''n''
matrix, each column is a cyclic shift of the first column.
The name comes from their use with
rotary encoder
A rotary encoder, also called a shaft encoder, is an electro-mechanical device that converts the angular position or motion of a shaft or axle to analog or digital output signals.
There are two main types of rotary encoder: absolute and increm ...
s, where a number of tracks are being sensed by contacts, resulting for each in an output of or . To reduce noise due to different contacts not switching at exactly the same moment in time, one preferably sets up the tracks so that the data output by the contacts are in Gray code. To get high angular accuracy, one needs lots of contacts; in order to achieve at least 1° accuracy, one needs at least 360 distinct positions per revolution, which requires a minimum of 9 bits of data, and thus the same number of contacts.
If all contacts are placed at the same angular position, then 9 tracks are needed to get a standard BRGC with at least 1° accuracy. However, if the manufacturer moves a contact to a different angular position (but at the same distance from the center shaft), then the corresponding "ring pattern" needs to be rotated the same angle to give the same output. If the most significant bit (the inner ring in Figure 1) is rotated enough, it exactly matches the next ring out. Since both rings are then identical, the inner ring can be cut out, and the sensor for that ring moved to the remaining, identical ring (but offset at that angle from the other sensor on that ring). Those two sensors on a single ring make a quadrature encoder. That reduces the number of tracks for a "1° resolution" angular encoder to 8 tracks. Reducing the number of tracks still further cannot be done with BRGC.
For many years, Torsten Sillke
and other mathematicians believed that it was impossible to encode position on a single track such that consecutive positions differed at only a single sensor, except for the 2-sensor, 1-track quadrature encoder. So for applications where 8 tracks were too bulky, people used single-track incremental encoders (quadrature encoders) or 2-track "quadrature encoder + reference notch" encoders.
Norman B. Spedding, however, registered a patent in 1994 with several examples showing that it was possible.
Although it is not possible to distinguish 2
''n'' positions with ''n'' sensors on a single track, it ''is'' possible to distinguish close to that many. Etzion and Paterson conjecture that when ''n'' is itself a power of 2, ''n'' sensors can distinguish at most 2
''n'' − 2''n'' positions and that for prime ''n'' the limit is 2
''n'' − 2 positions.
The authors went on to generate a 504-position single track code of length 9 which they believe is optimal. Since this number is larger than 2
8 = 256, more than 8 sensors are required by any code, although a BRGC could distinguish 512 positions with 9 sensors.
An STGC for ''P'' = 30 and ''n'' = 5 is reproduced here:
:
Each column is a cyclic shift of the first column, and from any row to the next row only one bit changes.
The single-track nature (like a code chain) is useful in the fabrication of these wheels (compared to BRGC), as only one track is needed, thus reducing their cost and size.
The Gray code nature is useful (compared to
chain code A chain code is a lossless compression based image segmentation method for binary images based upon tracing image contours. The basic principle of chain coding, like other contour codings, is to separately encode each connected component, or "blob" ...
s, also called
De Bruijn sequence
In combinatorial mathematics, a de Bruijn sequence of order ''n'' on a size-''k'' alphabet ''A'' is a cyclic sequence in which every possible length-''n'' string on ''A'' occurs exactly once as a substring (i.e., as a ''contiguous'' subseq ...
s), as only one sensor will change at any one time, so the uncertainty during a transition between two discrete states will only be plus or minus one unit of angular measurement the device is capable of resolving.
Two-dimensional Gray code
Two-dimensional Gray codes are used in communication to minimize the number of bit errors in
quadrature amplitude modulation
Quadrature amplitude modulation (QAM) is the name of a family of digital modulation methods and a related family of analog modulation methods widely used in modern telecommunications to transmit information. It conveys two analog message signa ...
(QAM) adjacent points in the
constellation. In a typical encoding the horizontal and vertical adjacent constellation points differ by a single bit, and diagonal adjacent points differ by 2 bits.
Two-dimensional Gray codes also have uses in
location identifications schemes, where the code would be applied to area maps such as a
Mercator projection of the earth's surface and an appropriate cyclic two-dimensional distance function such as the
Mannheim metric be used to calculate the distance between two encoded locations, thereby combining the characteristics of the
Hamming distance
In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. In other words, it measures the minimum number of ''substitutions'' required to chan ...
with the cyclic continuation of a Mercator projection.
Excess-Gray-Code
If a subsection of a specific codevalue is extracted from that value, for example the last 3 bits of a 4-bit gray-code, the resulting code will be an "excess gray code". This code shows the property of counting backwards in those extracted bits if the original value is further increased. Reason for this is that gray-encoded values do not show the behaviour of overflow, known from classic binary encoding, when increasing past the "highest" value.
Example: The highest 3-bit gray code, 7, is encoded as (0)100. Adding 1 results in number 8, encoded in gray as 1100. The last 3 bits do not overflow and count backwards if you further increase the original 4 bit code.
When working with sensors that output multiple, gray-encoded values in a serial fashion, one should therefore pay attention whether the sensor produces those multiple values encoded in 1 single gray-code or as separate ones, as otherwise the values might appear to be counting backwards when an "overflow" is expected.
Gray isometry
The bijective mapping establishes an
isometry
In mathematics, an isometry (or congruence, or congruent transformation) is a distance-preserving transformation between metric spaces, usually assumed to be bijective. The word isometry is derived from the Ancient Greek: ἴσος ''isos'' me ...
between the
metric space
In mathematics, a metric space is a set together with a notion of '' distance'' between its elements, usually called points. The distance is measured by a function called a metric or distance function. Metric spaces are the most general set ...
over the
finite field
In mathematics, a finite field or Galois field (so-named in honor of Évariste Galois) is a field that contains a finite number of elements. As with any field, a finite field is a set on which the operations of multiplication, addition, subtr ...
with the metric given by the
Hamming distance
In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. In other words, it measures the minimum number of ''substitutions'' required to chan ...
and the metric space over the
finite ring
In mathematics, more specifically abstract algebra, a finite ring is a ring that has a finite number of elements.
Every finite field is an example of a finite ring, and the additive part of every finite ring is an example of an abelian finite grou ...
(the usual
modular arithmetic
In mathematics, modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" when reaching a certain value, called the modulus. The modern approach to modular arithmetic was developed by Carl Friedrich Gauss in his boo ...
) with the metric given by the
Lee distance. The mapping is suitably extended to an isometry of the
Hamming space
In statistics and coding theory, a Hamming space (named after American mathematician Richard Hamming) is usually the set of all 2^N binary strings of length ''N''. It is used in the theory of coding signals and transmission.
More generally, a Ham ...
s
and
. Its importance lies in establishing a correspondence between various "good" but not necessarily
linear code In coding theory, a linear code is an error-correcting code for which any linear combination of codewords is also a codeword. Linear codes are traditionally partitioned into block codes and convolutional codes, although turbo codes can be seen as ...
s as Gray-map images in
of
ring-linear codes from
.
Related codes
There are a number of binary codes similar to Gray codes, including:
* Datex codes aka Giannini codes (1954), as described by Carl P. Spaulding,
use a variant of
O'Brien code II.
* Codes used by Varec (ca. 1954),
use a variant of
O'Brien code I as well as base-12 and base-16 Gray code variants.
* Lucal code (1959)
aka modified reflected binary code (MRB)
*
Gillham code
Gillham code is a zero-padded 12-bit binary code using a parallel nine- to eleven-wire interface, the Gillham interface, that is used to transmit uncorrected barometric altitude between an encoding altimeter or analog air data computer and a di ...
(1961/1962),
uses a variant of
Datex code and
O'Brien code II.
* Leslie and Russell code (1964)
* Royal Radar Establishment code
* Hoklas code (1988)
The following
binary-coded decimal (BCD) codes are Gray code variants as well:
* Petherick code (1953),
also known as
Royal Aircraft Establishment (RAE) code.
* O'Brien codes I and II (1955)
(An O'Brien type-I code
was already described by Frederic A. Foss of
IBM and used by
Varec in 1954. Later, it was also known as Watts code or Watts reflected decimal (WRD) code and is sometimes ambiguously referred to as reflected binary modified Gray code.
An O'Brien type-II code was already used by
Datex in 1954.
)
* Excess-3 Gray code (1956)
(aka Gray
excess-3
Excess-3, 3-excess or 10-excess-3 binary code (often abbreviated as XS-3, 3XS or X3), shifted binary or Stibitz code (after George Stibitz, who built a relay-based adding machine in 1937) is a self-complementary binary-coded decimal (BCD) cod ...
code,
Gray 3-excess code, reflex excess-3 code, excess Gray code,
Gray excess code, 10-excess-3 Gray code or Gray–Stibitz code), described by Frank P. Turvey Jr. of
ITT.
* Tompkins codes I and II (1956)
* Glixon code (1957), sometimes ambiguously also called modified Gray code
See also
*
Linear-feedback shift register
In computing, a linear-feedback shift register (LFSR) is a shift register whose input bit is a linear function of its previous state.
The most commonly used linear function of single bits is exclusive-or (XOR). Thus, an LFSR is most often a ...
*
De Bruijn sequence
In combinatorial mathematics, a de Bruijn sequence of order ''n'' on a size-''k'' alphabet ''A'' is a cyclic sequence in which every possible length-''n'' string on ''A'' occurs exactly once as a substring (i.e., as a ''contiguous'' subseq ...
*
Steinhaus–Johnson–Trotter algorithm
The Steinhaus–Johnson–Trotter algorithm or Johnson–Trotter algorithm, also called plain changes, is an algorithm named after Hugo Steinhaus, Selmer M. Johnson and Hale F. Trotter that generates all of the permutations of n elements. ...
– an algorithm that generates Gray codes for the
factorial number system
In combinatorics, the factorial number system, also called factoradic, is a mixed radix numeral system adapted to numbering permutations. It is also called factorial base, although factorials do not function as base, but as place value of digi ...
*
Minimum distance code
*
Prouhet–Thue–Morse sequence – related to inverse Gray code
*
Ryser formula
*
Hilbert curve
The Hilbert curve (also known as the Hilbert space-filling curve) is a continuous fractal space-filling curve first described by the German mathematician David Hilbert in 1891, as a variant of the space-filling Peano curves discovered by Giuseppe ...
Notes
References
Further reading
*
*
*
*
*
*
*
*
Part 2https://web.archive.org/web/20171030140323/https://www.eetimes.com/document.asp?doc_id=1278853 --> Part 3
* (7 pages)
* (5 pages)
* (2 pages)
*
External links
"Gray Code" demonstrationby Michael Schreiber,
Wolfram Demonstrations Project
The Wolfram Demonstrations Project is an organized, open-source collection of small (or medium-size) interactive programs called Demonstrations, which are meant to visually and interactively represent ideas from a range of fields. It is hos ...
(with Mathematica implementation). 2007.
NIST Dictionary of Algorithms and Data Structures: Gray code
including
C code to convert between binary and BRGC.
* Dragos A. Harabor use
Gray codes in a 3D digitizer
* Single-track gray codes, binary
chain code A chain code is a lossless compression based image segmentation method for binary images based upon tracing image contours. The basic principle of chain coding, like other contour codings, is to separately encode each connected component, or "blob" ...
s
Lancaster 1994, and
linear-feedback shift register
In computing, a linear-feedback shift register (LFSR) is a shift register whose input bit is a linear function of its previous state.
The most commonly used linear function of single bits is exclusive-or (XOR). Thus, an LFSR is most often a ...
s are all useful in finding one's absolute position on a single-track rotary encoder (or other position sensor).
AMS Column: Gray codesProtoTalk.net – Understanding Quadrature Encoding– Covers quadrature encoding in more detail with a focus on robotic applications
{{DEFAULTSORT:Gray Code
Data transmission
Numeral systems
Binary arithmetic
Non-standard positional numeral systems
Articles with example C code