Top Qs
Timeline
Chat
Perspective
Talk:Gray code/Archive 1
From Wikipedia, the free encyclopedia
Remove ads
![]() | This is an archive of past discussions about Gray code. Do not edit the contents of this page. If you wish to start a new discussion or revive an old one, please do so on the current talk page. |
Archive 1 |
Untitled
Summarize
Perspective
The following was at Gray_coding, and is moved here in case anyone wants to add some of it to the Gray_code article.
A gray code is a special coding system designed to prevent spurious output from practical electromechanical switches and is specifically relevant to encoding of position information for a rotating object. For example, if we create a device that indicates position by closing and opening switches, we could use the binary code to represent position:
Input position | Output 3 | Output 2 | Output 1 |
0 | 0 | 0 | 0 |
1 | 0 | 0 | 1 |
2 | 0 | 1 | 0 |
3 | 0 | 1 | 1 |
4 | 1 | 0 | 0 |
5 | 1 | 0 | 1 |
6 | 1 | 1 | 0 |
7 | 1 | 1 | 1 |
The problem is that, with real (mechanical) switches, it is very unlikely that two switches will change states exactly in synchrony. For example, in the transistion from state 3 to state 4, all three switches change state. In the brief period while all are changing, the switches will read some spurious position.
A gray code solves this problem by changing only one switch at a time, so there is never any ambiguity of position:
Input position | Output 3 | Output 2 | Output 1 |
0 | 0 | 0 | 0 |
1 | 0 | 0 | 1 |
2 | 0 | 1 | 1 |
3 | 0 | 1 | 0 |
4 | 1 | 1 | 0 |
5 | 1 | 1 | 1 |
6 | 1 | 0 | 1 |
7 | 1 | 0 | 0 |
Notice also that state seven can roll over to state zero with only one switch change.
I liked the less-technical introduction, so I copied it to the article.
I wish this article had a photo of an "encoder disk".
-- DavidCary 14:13, 12 Jun 2004 (UTC)
Remove ads
updates
Hi all, my first contribution to Wikipedia, hopefully it will go over well. I changed the example from a 4-bit BRGC to a 3-bit BRGC because it's a little bit simpler at first glance. I also added a lot of info about special types of Gray codes. Since this came from a paper I wrote, I added many of the references at the bottom that I used for the paper. I have some trivial C++ code to recursively generate an n-bit BRGC but I don't know if that would really be appropriate to attach to this. Thoughts? Rob 05:16, 6 Sep 2004 (UTC)
Remove ads
Real numbers?
Summarize
Perspective
Isn't it possible to give the real numbers a gray code representation? But the article only mentions integers. A5 18:42, 20 Apr 2005 (UTC)
- Maybe....though I had never heard of doing it. I suppose you can define a Gray code sequence for non-binary numbers such that only one digit changes. Following the same method for generating binary Gray codes, for trinary:
(trinary Gray code moved to main article)
You can extend this to decimal if you wish. Hmm, maybe I'll add trinary to the article. Cburnett 19:03, Apr 20, 2005 (UTC)
- This doesn't exactly answer the original question. You can have gray codes for other bases, but can you have one for the real numbers? The immediate answer seems to be no, since there's no such thing in the real numbers as two "successive" numbers. Deco 00:25, 21 Apr 2005 (UTC)
- You can represent real numbers in Gray code....but to finite precision. The point of the above is that you can easily find a Gray code for base 10 so its just if you care about infinite precision. Cburnett 01:25, Apr 21, 2005 (UTC)
- Gray codes are codes where neighbouring elements only differ in one symbol. On the real number line, there is no such thing as a neighbour - between any two numbers, there are infinitely many other numbers--Niels Ø 08:45, Apr 21, 2005 (UTC).
There are times when it is convenient to think of the bits from a sensor (whether it uses natural binary codes or gray codes) as bits of a binary fraction (i.e., a value from 0 to 1), rather than the bits of a binary integer.
Let's think about rotary encoders (like the one in the article) with 2, 3, 4, 5, 6, ... and N rings. (It doesn't matter what order the rings are in, so let's put the coarser rings nearer the center).
If you look carefully, the 7-ring encoder is just like the 8-ring coder with the 8th (outermost) ring filed off. The 6-ring encoder is just like the 7-ring encoder with the 7th (outermost) ring filed off.
If we represent these as fractional bits (rather than trying to make an integer out of them), it makes it easier to write software that can handle any kind of encoder (with any number of rings).
When encoder positions are represented as (fixed-point arithmetic) fractions such as
0.0100100111000000 and 0.0110110111000000
, software can find the angle between encoder position without needing to know exactly how many rings the encoder has. Then it is easy to upgrade to a more-precise encoder (more rings) or reduce cost by substituding a cheaper encoder (fewer rings), without changing any software.
When encoder positions are represented as integers such as
01001001110. and 01101101110.
, software needs to know exactly how many rings the encoder has, and usually needs to be re-compiled whenever the number of rings changes (which can be annoying).
Getting back to the original point: If you can give me a natural binary representation of a "real number", I can give you a (binary) Gray code representation of that number.
Does that answer the original question?
Is this something that should go into the article ?
--DavidCary 18:23, 14 May 2005 (UTC)
Remove ads
n-ary gray codes
Currently, two sections in the article deals with non-binary Gray codes. Both sections may have merit, so I guess they should be merged. --Niels Ø 08:24, Apr 21, 2005 (UTC)
- Doh, I missed the n-ary section. Merged. Cburnett 16:28, Apr 21, 2005 (UTC)
Are n-ary gray codes actually *used* for anything, or are they only interesting to mathematicians? --DavidCary 05:37, 6 November 2005 (UTC)
- An example: I'm generating a list of colours such that each colour is "nearby" to the next in RGB-space. If each coordinate can take n values, then an (n, 3)-Gray code is what I'm after. --Taejo|대조 13:21, 23 June 2007 (UTC)
Jos.koot 23:24, 23 November 2006 (UTC) : added a real working Scheme implementation of the algorithm together with an algorithm computing one single element of a Gray code and its inverse. In the pseudo algorithm the use of array n[k+1] is not needed and the arrays can be properly sized to k elements by halting when i grows out of range.
Remove ads
other applications of gray codes
Added some explanation on Gray Codes in Genetic Algorithms. -Shiri (a newbie)
am i correct in thinking
Summarize
Perspective
that a grey code cannot exist for a circular sequence with an odd number of values? Plugwash 01:43, 26 December 2005 (UTC)
- Correct. This is evident because going from one number to the next toggles one bit. An odd number of toggles cannot produce the original value; at least one bit must be different. Non-circular sequences are possible, of course. Deco 02:13, 26 December 2005 (UTC)
- What about the sequence (00, 01, 11, 10, 20, 21, 22, 12, 02)? --Pezezin 23:22, 30 June 2006 (UTC)
- The argument applies to binary Gray codes only. For larger bases, the situation is different.--Niels Ø 09:31, 24 November 2006 (UTC)
- What about the sequence (00, 01, 11, 10, 20, 21, 22, 12, 02)? --Pezezin 23:22, 30 June 2006 (UTC)
A remark should be added that cyclic ternary gray codes do exists for every k. (I don't know about (n,k) codes with n>3) Examples: (2,3) : (000 200 210 010 110 112 212 012 022 222 122 102 202 002 001 101 201 211 111 011 021 121 221 220 020 120 100)
(2,4): (0000 1000 1200 0200 2200 2210 0210 1210 1010 0010 2010 2110 0110 1110 1112 2112 0112 0212 2212 1212 1012 2012 0012 0022 2022 1022 1222 2222 0222 0122 2122 1122 1102 2102 0102 0202 2202 1202 1002 2002 0002 0001 1001 2001 2101 1101 0101 0201 1201 2201 2211 1211 0211 0111 1111 2111 2011 1011 0011 0021 1021 2021 2121 1121 0121 0221 1221 2221 2220 0220 1220 1020 0020 2020 2120 0120 1120 1100 0100 2100 2000)
These circular ternary gray codes can easily be produced by
(define (circular-ternary-gray-code k) (let-values (((f t r) (values 0 1 2))) ; permutations of 0, 1 and 2 generate different gray codes (define (long h f t r) (if (positive? h) (let ((h (sub1 h))) (long h f t r) (move h f r t) (long h t f r) (move h r t f) (long h f t r)))) (define (strt h f t r) (if (positive? h) (let ((h (sub1 h))) (strt h f r t) (move h f t r) (long h r t f)))) (define (fini h f t r) (if (positive? h) (let ((h (sub1 h))) (long h f r t) (move h f t r) (fini h r t f)))) (define result ()) (define pattern (make-vector k f)) (define (move h f t r) (vector-set! pattern h t) (set! result (cons (vector->list pattern) result))) (if (positive? k) (let ((h (sub1 k))) (strt h f r t) (move h f t r) (long h r f t) (move h t r f) (long h f t r) (move h r f t) (fini h t f r))) result))
Furthermore a O(k) algorithm exists for computing the i-th element of the gray codes produced by the above algorithm. The inverse exists too, i.e. a function that accepts a gray code and returns the i telling which element it is. In fact the ternary gray codes produced by the above algorithm show how to move a tower of hanoi Tower of hanoi from one peg back onto the same peg while passing every feasible distribution of disks exactly once (circular Hamilton path)
Jos.koot 13:40, 29 November 2006 (UTC)
Remove ads
Single-Track Gray Codes
It's the inner two tracks of Figure 1 that are the same except for an angular offset, and the inner track supplies the most significant bit. I have changed the text to correspond. It seems an unlikely error, though - has the figure been changed?
I made the same changes in the rotary encoder article.
- Jim Van Zandt
Are those programming examples really necessary?
If you think it would help, I could provide some alternative versions in Javascript, BASIC, FORTRAN and Z80 opcodes. We could even go the whole hog and and merge this page with the list of hello world programs. What do you reckon? -- Sakurambo 22:06, 17 May 2006 (UTC)
- Assuming you're being sarcastic, people have a bizarre tendency to add implementations in their favourite language to articles. Just cut out the ones you don't like. Deco 23:28, 30 June 2006 (UTC)
- The proposed languages are not bizarre enough for the bizarre tendency! If you can write it for Atanasoff-Berry Computer or at least in assembler for PDP-8/System360, it would be another story :-) Beyond the joke, I would say that all those implementations are subject to WikiBooks and should be moved there (leaving just a link here). -- Goldie (tell me) 20:49, 5 September 2006 (UTC)
- Or for my wiki, LiteratePrograms. </plug> :-) Deco 13:01, 20 November 2006 (UTC)
Remove ads
Gray code is not invented by Frank Gray
Frank Gray have not been born when the reflective binary code was invented. I do not know who have invented it either but the code was already in use in the mid-XIX century. In the Gray's patent it is clearly stated that he is claiming only the receiver and the implemented method for translation.
Elisha Gray does have some good chances to be the first who have put the code in an electrical aparatus but anyone's "invention" will have to be proved. I have no enough time to fix the name across the whole article. -- Goldie (tell me) 21:39, 5 September 2006 (UTC)
- There is no evidence to connect Elisha Gray to the Gray code, but several gray-code-like patterns and devices do pre-date Frank Gray's patent, according to the study by Don Knuth. Dicklyon 23:30, 23 November 2006 (UTC)
Code Bug
The following code can become an infinite loop:
In the programming language C, a conversion from a Gray code g to an unsigned binary representation b can be achieved efficiently through:
b = g; while (g >>= 1) {b ^= g;}
INTERNATIONAL STANDARD ISO/IEC 9899, Programming languages — C
6.5.7 Bitwise shift operators
4 The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 ´ 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 ´ 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
5 The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined. —The preceding unsigned comment was added by Crm123 (talk • contribs) 17:24, 7 May 2007 (UTC).
Remove ads
gray code toy worth a mention?
The Brain Puzzler was a mechanical toy produced in the 1970s or early 80s. The solution to the puzzle was a RBGC. Worth a link from the article? 216.220.208.238 16:24, 15 December 2006 (UTC)
The "Tower of hanoi" external link is dead (404).
Single track Gray code image
I've added an image to the section, corresponding with the table, but I'm too lazy to write a caption. Shinobu 11:14, 17 May 2007 (UTC)
- Is that the image that the text in that section is calling "Figure 1"? Rather than refer to the figure, the figure needs a caption that calls to the reference.
No, figure 1 refers to the normal rotary encoder. Shinobu 08:39, 11 June 2007 (UTC)
haskell code?
Summarize
Perspective
Quoting the article :
(The base case can also be thought of as a single zero-bit Gray code (n=0, G = { " " }) which is made into the one-bit code by the recursive process, as demonstrated in the Haskell example below).
I don't see any haskell code in the article. Anyone does? Stdazi (talk) 09:06, 18 August 2008 (UTC)
- I have added some Haskell code, if someone thinks that this code is in wrong place, cut and paste as is to move it.
I had some problems to format this code, because wiki translated lists to links. The style is very simple, because I take into account that imperative languages programers are not familiar with recursive definitions, much more less with higher order functions. But, I used map, a higher order function, if you think it obscures the program, change transpose to:
transpose :: [ anytype_t ] -> [ anytype_t ] transpose [] = [] transpose ([]:xss) = [] transpose ((x:xs):xss)= (heads ((x:xs):xss)):(transpose (tails ((x:xs):xss))) where heads [] = [] heads (x:xs) = (head x):(heads xs) tails [] = [] tails (x:xs) = (tail x):(tails xs)
or let them search more about haskell and map in Wikipedia :) —Preceding unsigned comment added by Elias (talk • contribs) 04:30, 3 January 2009 (UTC)
Algorithm correct?
Summarize
Perspective
A test using Java with grayN(21, 3, 3) gives me: {-1,2,2}
Obviously that is not correct!
Using this code:
static int[] grayN(int value, int base, int digits) { // parameters: value, base, digits // Convert a value to a graycode with the given base and digits. Iterating // through a sequence of values would result in a sequence of graycodes in // which only one digit changes at a time. int baseN[] = new int[digits]; // Stores the ordinary base-N number, one digit per entry int gray[] = new int[digits]; // Stores the base-N graycode number int i; // Put the normal baseN number into the baseN array. For base 10, 109 // would be stored as [9,0,1] for (i = 0; i < digits; i++) { baseN[i] = (value / (int) Math.pow(base, i)) % base; } // Convert the normal baseN number into the graycode equivalent. Note that // the loop starts at the most significant digit and goes down. int shift = 0; for (i = digits - 1; i >= 0; i--) { // The gray digit gets shifted down equal to the sum of the higher // digits. gray[i] = (baseN[i] + base - shift) % base; // + base to prevent neg shift += gray[i]; } return gray; }
Is my code wrong, or is there a bug in the algorithm shown on the article? —CobraA1 01:15, 13 February 2009 (UTC)
- The C code is wrong in some senses. First, the first loop gets the digits in the reverse order to the stated one; the comment is right as is your code, but the C code does it wrong. Second, just adding base does not avoid negatives. Third, it does not declare the loop variable. I'm fixing all these issues, but ultimately I think this fragment should be replaced by pseudocode or a description. --pgimeno (talk) 16:21, 7 August 2009 (UTC)
Code snippets
Summarize
Perspective
Why so many code snippets? Most of them are not even particularly intelligible. I bet if we wanted clarity and precision, then matlab code would beat them all. Any opinions? Dicklyon 06:58, 10 December 2006 (UTC)
For example, compare this to the others to convert binary B to Gray G:
G = bitxor(B, bitshift(B, -1));
The other direction probably requires a loop and more bit twiddling, though. Dicklyon 07:11, 10 December 2006 (UTC)
OK, even though I wasn't kidding, I take it back. Reading the talk above, I took the suggestion and removed the ones I didn't like, which was all of them. Pseudocode is enough, since the details of the others only obscure the point, except for programmers who know the language; and they don't need it. Dicklyon 07:21, 10 December 2006 (UTC)
- I am totally in favour of this. Gray codes are generally used in electronic hardware, so personally I don't see the need for any software examples at all. -- Sakurambo 桜ん坊 11:25, 10 December 2006 (UTC)
- Well, now that hardware is usually designed by writing Verilog code, code is the lingua-franca of algorithms, so we really out to have something. But showing off programming language features and syntax is not the point. Dicklyon 17:31, 10 December 2006 (UTC)
- I would like to add here that LISP is one of those languages famous for being unreadable to someone unfamiliar with it. Pseudocode? Better formatting? I'll leave it to you all, but as it stands I didn't find the snippets very illuminating. Shinobu 11:37, 17 May 2007 (UTC)
- Well, now that hardware is usually designed by writing Verilog code, code is the lingua-franca of algorithms, so we really out to have something. But showing off programming language features and syntax is not the point. Dicklyon 17:31, 10 December 2006 (UTC)
Would it be okay to bring back one pseudo-code (or C-like language) example for encoding, and one example for decoding? I actually came back to this page looking for them, since it is useful sometimes for encoding integers in genetic algorithms. I do agree that previously there were too many, and it was messy, but I think a single snippet for each of encoding/decoding would be nice. Fstonedahl (talk) 20:52, 11 January 2009 (UTC)
The useful 'C-like' language for a web page is JavaScript. There could be code snippets which actually demonstrate something in the browser: an edit box to a text output, for example. —Preceding unsigned comment added by 81.108.210.118 (talk) 09:31, 8 October 2009 (UTC)
Iterative construction
I came to this page looking for the information below, and didn't find it, so I added it in the section Constructing an n-bit gray code. I don't think I explained it brilliantly though, so I'd appreciate improvements.
- To construct the binary-reflected Gray code iteratively, start with the code 0, and at step i find the bit position of the least significant '1' in the binary representation of i - 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, ... (sequence A007814 in the OEIS).
Motivation: I'm writing code that needs to traverse all 2edges possible graphs of n nodes, and easiest is to change one edge at a time from the previous graph. Hv (talk) 12:12, 2 January 2010 (UTC)
another example
http://blog.plover.com/2009/06/21/ (maybe this is worth adding it) —Preceding unsigned comment added by 91.37.9.19 (talk) 23:51, 21 June 2009 (UTC)
The conversion methods in the last couple of lines are interesting, but the small error described in the bulk of the article is chance: the height happened to occur where the least significant bit changed; if it had occurred where the most significant bit changed the reading could be very inacurate! —Preceding unsigned comment added by 81.108.210.118 (talk) 09:43, 8 October 2009 (UTC)
Examples please
Snakes and coils - in the Snake-in-the-box codes section - sound interesting - but what do they look like? Not every reader capable of understanding the description has the chops to actually construct something from an abstract definition. If anyone could add an example or two of each of these objects, it would communicate the notions involved much better. Simple folk like me need plenty of concrete examples to wrap my head around. ;-) yoyo (talk) 10:07, 9 June 2010 (UTC)
Iterative construction cleanup.
Summarize
Perspective
Some proposed wording: Informally, to construct a Gray code on n bits from one on n - 1 bits, take the previous Gray code and list the elements first in order, then in reverse order. Prepend a 0 to the elements that are listed in order, and a 1 to the elements that are listed in reverse order.
Somewhat more formally, let Gn be the canonical Gray code on n bits, let Gn(k) be the k-th entry in the code, where 0 ≤ k < 2n, and let #Gn(k) be the k-th entry of the code preceded by # (where # is either 1 or 0). The following constructs the canonical Gray code on n bits:
G1 = (0, 1).
If n > 1, then:
- If 0 ≤ k ≤ 2n - 1 - 1, then Gn(k)=0Gn - 1(k).
- If 2n - 1 ≤ k ≤ 2n - 1, then Gn(k)=1Gn-1(2n - (k + 1)).
So G2(0) = 0G1(0) = 00. Similarly, G2(1) = 0G1(1) = 01.
How does this sound? --147.26.161.144 (talk) 20:51, 18 July 2010 (UTC)
- The first paragraph is OK. The subsequent formalism doesn't contribute much: harder to understand and less helpful than the current text. The [01]G(n) notation feels sort of ad hoc. The example could be more illustrative (e.g., pick one of the values from the reversed sequence). (I am, of course, not exactly a disinterested party!) -- Elphion (talk) 16:53, 19 July 2010 (UTC)
- My use of the phrase "iterative construction" was intended to convey the concept of "determining the next value from the previous one". Your proposal however looks to be a rewrite of the presentation of the recursive algorithm at the start of the Constructing an n-bit Gray code section, which already seems to me quite adequate as it stands. What issue are you aiming to address with this? Hv (talk) 09:22, 21 July 2010 (UTC)
Connection to symbolic dynamics
I'd like to hint at a connection with Symbolic dynamics, specifically the Tent map. A sort of Gray code of real numbers is constructed as follows. Let be the Tent map with slope 2 and be a set of symbols. Define an address map by letting whenever , only for and otherwise. Then the infinite Gray code of is given as the sequence . This sequence is an element of the so-called Shift space . Now, for an integer with consider the real number . Then the m-digit Gray code of is the first m digits of the sequence defined above. 80.1.165.108 (talk) 01:04, 26 March 2011 (UTC) O. Klinke, University of Birmingham, UK
Incorrect link to Chain code?
In Gray code#Single-track Gray code, there is "(compared to chain codes, also called De Bruijn sequences)". But the chain codes described at that article are for compressing monochrome images and seem unrelated to De Bruijn sequences. There's also a reference to “code chains”. Could someone more familiar with this material correct these links or add explanation of how they're related? — Unbitwise (talk) 21:03, 22 June 2011 (UTC)
Vietnamese-rings puzzle?
The binary-reflected Gray code can also be used to serve as a solution guide for the Tower of Hanoi problem, as well a classical Vietnamese-rings puzzle and a sequential mechanical puzzle mechanism. Apart from the unclear syntax ("as well a" = as well as for a?), what is a classical Vietnamese-rings puzzle? Some variant of the Chinese rings puzzle?--85.75.178.41 (talk) 11:27, 23 June 2011 (UTC)
Irrelevant reference?
The reference "Venn Diagram Survey — Symmetric Diagrams" for the sentence "Note that each column is a cyclic shift of the first column, and from any row to the next row only one bit changes." in the Single-track Gray code section makes no sense to me in relation to that sentence. I'm not familiar with Venn Diagrams, but as far as I can tell the reference doesn't relate in any way to the subject. Am I correct? If not, what is the relation? -- Sjock (talk) 20:32, 28 September 2011 (UTC)
Simple conversion to binary
I read this page for a class assignment and noticed that most algorithms were in needlessly complicated code form. I found that the slides on this website did a much better job at explaining how to convert between binary and Gray. Therefore I propose to add an example (sub)section which basically reads something like this: assume you have a Gray code (X3,X2,X1,X0) = 1010 and would like to convert it to binary(Y3,Y2,Y1,Y0), then Y3 = X3 and Y2 = X2 XOR Y3, Y1 = X1 XOR Y2 ... Y[n] = X[n] XOR Y[n+1] ==> Y1,Y2,Y3,Y4 = 1100. Likewise, to go from binary to Gray, X3 = Y3, X2 = Y3 XOR Y2... I admit, I do not know the rules of WP very well and this is the first time editing anything other than typos, but would anyone have any problems with this addition? — Preceding unsigned comment added by 98.249.63.58 (talk) 02:32, 3 October 2011 (UTC)
- Looks like a reliable source, and I don't see an equivalently simple method in the article, so it looks like it might be a good addition. Dicklyon (talk) 05:14, 3 October 2011 (UTC)
- The last few paragraphs of the construction section already say this. I agree it could be said more clearly. The bit-by-bit formulas already present should be incorporated into any new discussion. It would help to relate the two conversions more clearly to the preceding theoretical construction (which makes clear that Gray codes have the properties they do). -- Elphion (talk) 13:51, 3 October 2011 (UTC)
Ternary Gray Code
The section explains that other gray codes exist but would benefit from at least one example. Since the given algorithm is cyclic, perhaps a reflected version would help make the point. Is this a viable alternative?:
0 -> 000 1 -> 001 2 -> 002 10 -> 012 11 -> 011 12 -> 010 20 -> 020 21 -> 021 22 -> 022 100 -> 122 101 -> 121 102 -> 120 110 -> 110 111 -> 111 112 -> 112 120 -> 102 121 -> 101 122 -> 100 200 -> 200 201 -> 201 202 -> 202 210 -> 212 211 -> 211 212 -> 210 220 -> 220 221 -> 221 222 -> 222
81.108.210.118 (talk) 11:06, 9 October 2009 (UTC)
Anti-Gray Codes?
Summarize
Perspective
Is there a code where the bit patterns of successive elements differ from each other by a maximal, rather than minimal, number of bits?
The problem with Gray codes for positional measurements is that you're vulnerable to misreads: if you get some birdshit on one of your black blobs and it goes white, for instance, if it's the bit that differs between that position and one of its neighbours, you can no longer detect that transition. Ditto if your photocell is flaky or something. With an anti-Gray code, you have multiple bits changing at every transition, so you're much more likely to detect it. If you have a shitty photocell or a shitted-on mark, you won't get the pattern you expected, but you will get a transition to an unexpected state - at which point you declare an error condition, call the repairman or cleaner, and either stop or or take a gamble on being where you think you should be, and hope the next transition works out.
Kind of like 8b/10b encoding if you think about it in precisely the wrong way.
-- Tom Anderson 2007-09-19 2330 +0100 —Preceding unsigned comment added by 128.40.81.22 (talk) 22:31, 19 September 2007 (UTC)
If you consider the recursive method for Gray Code construction, one solution to creating "Anti-Gray Codes" is to add 01010101... instead of 00000...11111... to the code at every step. E.g.: (0, 1), (00, 11, 01, 10), (000, 111, 001, 110, 010, 101, 011, 100)... this creates a large distance between adjacent codes, but not necessarily between further codes.72.231.157.16 (talk) 05:27, 18 April 2009 (UTC)
- While that does create some distance you'll notice that many of your generated numbers share several bits from the 4th place on. 110,010 is a hamming distance of 1. Optimally anti-gray code for a set of three binary numbers will always alternate between hamming distances of 2 and 3. 000,111,001,110,101,010,100,011 you'll note is better having hamming distances of 3,2,3,2,3,2,3. Tat (talk) 23:17, 17 August 2012 (UTC)
Took me a while to figure it out, I needed one too.
Take any gray code. Shift all the bits to the left by 1. Double the list. And alternate XOR flips. Done. You have an anti-gray code.
Take gray code. 0 1
Shift all the bits to the left by 1. 00 10
Double the list. 00 00 10 10
Alternate XOR flips. 00 11 10 01
The reason this works is because gray codes by definition have the minimal amount of distance. Xor flips have the maximum (they flip every bit). If you interweave them you will have maximum, maximum -1, maximum, maximum -1, maximum, maximum -1... which is an optimal anti-gray code. Also note, you don't really *need* to shift the bits to the left. You can introduce a zero *anywhere*, so long as you do it consistently. Watch, I'll do it with the middle digit.
00,01,11,10
-> 000,001,101,100 -> 000,000,001,001,101,101,100,100 -> 000,111,001,110,101,010,100,011 (perfect anti-grey code).
Fast conversion to binary
Summarize
Perspective
This is an implementation of n.log(n) conversion in C designed to be independent of the type width.
unsigned short grayToBinary(unsigned short num)
{
unsigned short shift, mask;
for(shift=1; mask=num>>shift-1>>1; shift<<=1)
num ^= mask;
return num;
}
Is it worth of replacing the current example? --egg 22:11, 3 November 2011 (UTC)
- Am I dense, or is the expression num>>shift-1>>1 nonsensical? And why don't you put some spaces around binary operators, and maybe some courtesy parens, to give us a clue what it means? I expect it means (num >> (shift - 1)) >> 1, but it's unclear to me how that differs from num >> shift; sorry I'm not more familiar with c semantics. And it's not clear when/why this loop terminates; for 16-bit shorts, you'd want shift values of 1, 2, 4, 8, but it goes on through 16, 32, 64, ... 32768, doesn't it? Dicklyon (talk) 05:54, 4 November 2011 (UTC)
The expression essentially means num>>shift but the >> operator has undefined behaviour for shifts longer or equal to the width of type, which is the case we need to stop the loop. This might be a more readable version of the same algorithm:
unsigned short grayToBinary(unsigned short num)
{
unsigned short shift;
for(shift=1; shift<8*sizeof(num); shift*=2)
num ^= num>>shift;
return num;
}
Both versions work well. BTW, why do we use the short type instead of the common unsigned int?.. --egg 13:20, 4 November 2011 (UTC)
The second example is far superior to the first. (The first completely obscures the principle being illustrated.) Applying the principle of self-documenting code, how about:
unsigned short grayToBinary(unsigned short num)
{
unsigned short shift;
unsigned short numBits = 8 * sizeof(num);
for(shift=1; shift<numBits; shift*=2) {
num ^= num>>shift;
}
return num;
}
A final version should include something like the documentation in the example in the article. It's probably worth a comment that the algorithm assumes that the bitwidth of the argument is a power of 2. (I've worked on machines where that's not true.) Why "unsigned short"? That's the likely domain of discourse. ints are probably overkill, though the additional execution cost wouldn't amount to much. In C++ you might accommodate both with templates. -- Elphion (talk) 15:10, 4 November 2011 (UTC)
- Yes, much better. I'd style it nicer and use int though: Dicklyon (talk) 15:54, 4 November 2011 (UTC)
unsigned int grayToBinary(unsigned int num)
{
unsigned int numBits = 8 * sizeof(num);
unsigned int shift;
for (shift = 1; shift < numBits; shift *= 2)
{
num ^= num >> shift;
}
return num;
}
Correction
As user:Mikron30 has pointed out, this version does not work: it converts 12 to 9 rather than to the correct value (8). The problem is that num should be XORed with the shift of its original value, not of its current value, as follows:
unsigned int grayToBinary(unsigned int num)
{
unsigned int numBits = 8 * sizeof(num);
unsigned int shift;
unsigned int mask = num;
for (shift = 1; shift < numBits; shift *= 2)
{
num ^= mask >> shift;
}
return num;
}
Since in this case mask will always shift eventually to 0, it suffices to loop while mask is non-zero. Counting the bits is not necessary. I've updated the algorithm in the article accordingly.
How many Gray codes are there?
I was asked recently how many distinct binary Gray codes there are are n bits. Given the canonical Gray code on n bits, you can easily create (2^n)*n! Gray codes by choosing any of the 2^n vertices as starting points, and permuting the columns of bitflips. Example, if the bits are numbered from right to left as this: 4 3 2 1, then the Gray code on 4 bits is made by flipping the following positions in order: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1. Now this can be permuted by anything in S4, so for any of the 16 starting points, there are 24 Gray codes. Does this hit all possible ones? If so, they are all isomorphic to the canonical one, and the formula is nice. If not, then the problem is more interesting. --147.26.161.144 (talk) 20:23, 18 July 2010 (UTC)
There are many more because the ones you described are “only” those for one specific transition-sequence. The section types of Gray codes describes many more possible sequences. Every single one of those has, again, different code-representations. — Preceding unsigned comment added by 91.112.63.30 (talk) 12:46, 24 June 2013 (UTC)
Gillham code
I have been searching and searching for hours and did not find any theory behind Gillham code which is another type of Gray code. Gillham code is used in aviation altitude encoders/ transponders. I would really appreciate if someone could post some info on Gillham code, conversion algorithm, etc... —Preceding unsigned comment added by Myval (talk • contribs) 07:29, 25 September 2008 (UTC)
- I agree that this "Gray code" article should at least mention Gillham code. But now that we have a Gillham code article, that article would be a better place for details about it. --DavidCary (talk) 17:53, 25 June 2013 (UTC)
- I would also like to see a reference to Gillham code and to its application in aviation, as this is IMHO one of the most important applications of a type of Gray code - Sswitcher (talk) 08:21, 16 June 2014 (UTC)
PCM tube?
Should PCM tube reference Pulse Code Modulation or the subsection on that page? — Preceding unsigned comment added by 59.167.182.149 (talk) 03:09, 13 December 2014 (UTC)
Baudot code, one of the first use of Gray code
Gray code code example changes
"for" loop vs. "while" loop and the superfluous shift operation
Superfluous exclusive or in grayToBinary code example
Lucal code?
Animation
Example image
Source code?
Edit request
Gray code and incremental encoders
Varec codes?
Excess-3 or Stibitz sources
Proposal: Rotate table in "Related codes"
Wikiwand - on
Seamless Wikipedia browsing. On steroids.
Remove ads