MarketGray code
Company Profile

Gray code

The reflected binary code (RBC), also known as reflected binary (RB) or Gray code after Frank Gray, is an ordering of the binary numeral system such that two successive values differ in only one bit.

Function
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, 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 system, possibly via combinational logic, 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 integers, 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 of 1 between adjacent codes. == Invention ==
Invention
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 code for non-negative integers, the binary-reflected Gray code, or BRGC. Bell Labs researcher George R. Stibitz described such a code in a 1941 patent application, granted in 1943. Frank Gray 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". of a tesseract In the standard encoding of the Gray code the least significant bit follows a repetitive pattern of 2 on, 2 off the next digit a pattern of 4 on, 4 off; the i-th least significant bit a pattern of 2i on 2i off. The most significant digit is an exception to this: for an n-bit Gray code, the most significant digit follows the pattern 2n−1 on, 2n−1 off, which is the same (cyclic) sequence of values as for the second-most significant digit, but shifted forwards 2n−2 places. 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, Gray codes play an important role in error correction. For example, in a digital modulation scheme such as QAM where data are typically transmitted in symbols of four bits, or more, the signal's constellation diagram 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. 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 is sometimes misattributed to 19th century electrical device inventor Elisha Gray. == History and practical application ==
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, a sequential mechanical puzzle mechanism described by the French Louis Gros in 1872. Telegraphy codes When the French engineer Émile Baudot changed from using a 6-unit (6-bit) code to 5-unit code for his printing telegraph 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 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, 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-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 for angle-measuring devices marked in 3-bit binary-reflected Gray code (BRGC) Gray codes are used in linear and rotary position encoders (absolute encoders and quadrature encoders) 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 properties of Gray codes, they are sometimes used in genetic algorithms. They may be useful in this field because 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 maps 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, 1D- and 2D-Gray codes play an important role in error prevention before applying an error correction. For example, in a digital modulation scheme such as QAM where data is typically transmitted in symbols of 4 bits or more, the signal's constellation diagram 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. QPSK Gray Coded.svg|Codes 4-PSK 8PSK Gray Coded.svg|Codes 8-PSK 16QAM Gray Coded.svg|Codes 16-QAM 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 sequentially 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. 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 executable code typically causes an instruction memory access pattern of locally consecutive addresses, bus encodings 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. Evenness and Oddness of Gray codes In the natural binary code system, the least significant bit indicates if the number is even (0) or odd (1), a property absent in the Gray code. Because just one bit is changed in consecutive Gray codes, the number of 1 bits will alternate between even and odd, so, to check a Gray code's evenness, it's necessary to count them, that is, an even number of 1s means the Gray code is even: Some processors, like Zilog's Z80, Japan ASCII's R800, and Intel's 8086, have parity status flags, which indicate bitwise evenness of some registers, facilitating checking if the number of up bits in them is even. == Constructing an n-bit Gray code ==
Constructing an n-bit Gray code
The binary-reflected Gray code list for n bits can be generated recursively 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 G1 = (). This can be thought of as built recursively as above from a zero-bit Gray code G0 = ( Λ ) consisting of a single entry of zero length. This iterative process of generating Gn+1 from Gn makes the following properties of the standard reflecting code clear: • Gn is a permutation of the numbers 0, ..., 2n − 1. (Each number appears exactly once in the list.) • Gn is embedded as the first half of Gn+1. • Therefore, the coding is stable, in the sense that once a binary number appears in Gn 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 mth reflecting Gray code, counting from 0. • Each entry in Gn differs by only one bit from the previous entry. (The Hamming distance is 1.) • The last entry in Gn 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 nth Gray code is obtained by computing n \oplus \left\lfloor \tfrac{n}{2} \right\rfloor. 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 i of codewords are inverted, the order of neighbouring blocks of 2^i codewords is reversed. For example, if bit 0 is inverted in a 3 bit codeword sequence, the order of two neighbouring codewords is reversed {{block indent|{} → {} (invert bit 0)}} If bit 1 is inverted, blocks of 2 codewords change order: {{block indent| {} → {} (invert bit 1)}} If bit 2 is inverted, blocks of 4 codewords reverse order: {{block indent| {} → {} (invert bit 2)}} Thus, performing an exclusive or on a bit b_i at position i with the bit b_{i+1} at position i+1 leaves the order of codewords intact if b_{i+1} = \mathtt{0}, and reverses the order of blocks of 2^{i+1} codewords if b_{i+1} = \mathtt{1}. 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 g_i is the ith Gray-coded bit (g_0 being the most significant bit), and b_i is the ith binary-coded bit (b_0 being the most-significant bit), the reverse translation can be given recursively: b_0 = g_0, and b_i=g_i \oplus b_{i-1}. Alternatively, decoding a Gray code into a binary number can be described as a prefix sum 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 \mathrm{code}_0 = \mathtt{0}, and at step i > 0 find the bit position of the least significant in the binary representation of i and flip the bit at that position in the previous code \mathrm{code}_{i-1} to get the next code \mathrm{code}_i. The bit positions start 0, 1, 0, 2, 0, 1, 0, 3, ... See find first set for efficient algorithms to compute these values. == Converting to and from Gray code ==
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) { return num ^ (num >> 1); // The operator >> is shift right. The operator ^ is exclusive or. } // This function converts a reflected binary Gray code number to a binary number. uint GrayToBinary(uint num) { uint mask = num; while (mask) { // Each Gray code bit is exclusive-ored with all more significant bits. mask >>= 1; num ^= mask; } return 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) { num ^= num >> 16; num ^= num >> 8; num ^= num >> 4; num ^= num >> 2; num ^= num >> 1; return 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. 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 ==
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 of 1 from the next word). Gray codes with n bits and of length less than 2n 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 sequence A290772 gives the number of possible Gray sequences of length that 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 {}. 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 2\left\lfloor \tfrac{2^n}{2n} \right\rfloor or 2\left\lceil \tfrac{2^n}{2n} \right\rceil. Monotonic Gray codes Monotonic codes are useful in the theory of interconnection networks, especially for minimizing dilation for linear arrays of processors. based on previous work, was designed by etzenseep (Florian Bauer) in September 2022. An STGC for P = 360 and n = 9 is reproduced here: Two-dimensional Gray code Two-dimensional Gray codes are used in communication to minimize the number of bit errors in quadrature amplitude modulation (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 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 ==
Gray isometry
The bijective mapping { 0 ↔ , 1 ↔ , 2 ↔ , 3 ↔ } establishes an isometry between the metric space over the finite field \mathbb{Z}_2^2 with the metric given by the Hamming distance and the metric space over the finite ring \mathbb{Z}_4 (the usual modular arithmetic) with the metric given by the Lee distance. The mapping is suitably extended to an isometry of the Hamming spaces \mathbb{Z}_2^{2m} and \mathbb{Z}_4^m. Its importance lies in establishing a correspondence between various "good" but not necessarily linear codes as Gray-map images in \mathbb{Z}_2^2 of ring-linear codes from \mathbb{Z}_4. == Related codes ==
Related codes
There are a number of binary codes similar to Gray codes, including: • Datex codes or Giannini codes (1954), as described by Carl P. Spaulding, use a variant of O'Brien code II. • Codes used by Varec (c. 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 (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 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 ==
tickerdossier.comtickerdossier.substack.com