Talk:Gray code/Archive 1

message: 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:
Binary Code
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:
Gray Code
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)
thread_title: Untitled

message: 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)
thread_title:  updates 

message: 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)
replies: text: 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)
thread_title:  n-ary gray codes 

message: that a grey code cannot exist for a circular sequence with an odd number of values? Plugwash 01:43, 26 December 2005 (UTC)
replies: text: 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)
replies: text: What about the sequence (00, 01, 11, 10, 20, 21, 22, 12, 02)? --Pezezin 23:22, 30 June 2006 (UTC)
replies: text: The argument applies to binary Gray codes only. For larger bases, the situation is different.--Niels Ø 09:31, 24 November 2006 (UTC)
thread_title:  am i correct in thinking 

message: 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)
replies: text: 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)

text: 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)
replies: text: Or for my wiki, LiteratePrograms. </plug> :-) Deco 13:01, 20 November 2006 (UTC)
thread_title:  Are those programming examples ''really'' necessary? 

message: 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)
replies: text: 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)
thread_title:  Gray code is not invented by Frank Gray 

message: 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)
thread_title: Code Bug

message: 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)
thread_title: gray code toy worth a mention?

message: 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)
replies: text: 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)
thread_title:  Single track Gray code image 

message: 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)
thread_title:  haskell code? 

message: 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)
replies: text: 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)
thread_title:  Algorithm correct? 

message: 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)
replies: text: 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)
replies: text: 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)
replies: text: 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)
thread_title: Code snippets

message: 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, ... .
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)
thread_title:  Iterative construction 

message: 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)
replies: text: You are completely wrong.  The whole point of gray code is that there isn't a "most significant" bit.  —Dominus (talk) 12:44, 3 January 2010 (UTC)
thread_title:  another example 

message: 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)
thread_title:  Examples please 

message: 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)
replies: text: 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)

text: 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)
thread_title:  Iterative construction cleanup. 

message: I'd like to hint at a connection with Symbolic dynamics, specifically the Tent map. 
A sort of Gray code of real numbers x \in [0,1] is constructed as follows.
Let T: [0,1] \rightarrow [0,1] be the Tent map with slope 2 and \Omega = \{0,c,1\} be a set of symbols. 
Define an address map A: [0,1] \rightarrow \{0,c,1\} by letting A(x) = 0 whenever x < \frac{1}{2}, 
A(x) = c only for x=\frac{1}{2} and A(x) = 1 otherwise. 
Then the infinite Gray code of x is given as the sequence g_n(x) = A(T^n(x)). 
This sequence is an element of the so-called Shift space \Omega^\mathbb{N}.
Now, for an integer k with k < 2^m  consider the real number x = \frac{k}{2^m - 1} . 
Then the m-digit Gray code of k is the first m digits of the sequence g_n(x) defined above.
80.1.165.108 (talk) 01:04, 26 March 2011 (UTC)
thread_title:  Connection to symbolic dynamics 

message: 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)
thread_title:  Incorrect link to [[Chain code]]? 

message: 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)
thread_title:  Vietnamese-rings puzzle? 

message: 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)
thread_title:  Irrelevant reference? 

message: 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)
replies: text: 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)
replies: text: 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)
thread_title:  Simple conversion to binary 

message: 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)
replies: text: I first had the same idea: on each digit position, alternate 0,1,2,2,1,0 (like the binary sequence 0,1,1,0). But because 3 is not a multiple of 2, the code can NOT be cyclic this way: 22 is too far from 00, 222 is too far from 000, etc. Teuxe (talk) 16:31, 20 January 2012 (UTC)
thread_title: Ternary Gray Code

message: 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)
replies: text: 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)
thread_title:  Anti-Gray Codes? 

message: 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)
replies: text: 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)
replies: text: Plus I'm dense.  I see why I misinterpreted now.  Dicklyon (talk) 15:54, 4 November 2011 (UTC)

text: Yes, much better.  I'd style it nicer and use int though: Dicklyon (talk) 15:54, 4 November 2011 (UTC)
thread_title:  Fast conversion to binary 

message: 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. 
-- Elphion (talk) 06:49, 15 April 2013 (UTC)
thread_title:  Correction 

message: 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)
thread_title:  How many Gray codes are there? 

message: 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)
replies: text: 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)

text: 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)
thread_title:  Gillham code 

message: 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)
replies: text: Yes; but what subsection do you have in mind?  Dicklyon (talk) 03:45, 13 December 2014 (UTC)
thread_title:  PCM tube? 

message: @84.153.139.186, thank you for your ongoing edits to the Gray code article.  It appears to me that you are advocating for a switch from a "for" loop to a "while" loop because it "removed superfluous shift operation".  Is that right?  Unfortunately, I fear that your counting is off.  In one case, the first shift occurs when "mask" is first set and in the other case it occurs after "mask" has been first set to "num".  Either way that counts as 1.  The remaining shifts do not depend upon "for" or "while" and continue exactly until "mask" becomes zero.
Because I am not seeing any speed advantage to one formulation over the other, to me it then boils down to a comparison of which code is clearer.  Since the loop has an initialization ("mask = num" or "mask = num >> 1") and an update step on the same variable ("mask = mask >> 1"), would you agree that the "for" loop captures that well?  64.132.59.226 (talk) 14:59, 2 November 2017 (UTC)
replies: text: OUCH! The former "for" loop had the disadvantage to perform a superfluous shift operation when num == 0, alias always performs an initial shift operation, even when not necessary, produces two shift instructions, and the result of the last shift is never used. Additionally the initial shift obscures how the algorithm works.84.153.128.88 (talk) 04:32, 4 November 2017 (UTC)
replies: text: The while version is easier to read and interpret, esp. for non C programmers, and no less efficient, shifting exactly the same number of times until mask gets to 0 (and efficiency is certainly not a consideration here). Dicklyon (talk) 01:38, 4 November 2017 (UTC)
replies: text: Thank you for the clarification that the while loop implementation saves a shift operation only in the case that num equals 0, and that this comes at the expense of an extra comparison against zero when num is not equal to 0. 64.132.59.226 (talk) 13:08, 6 November 2017 (UTC)
thread_title:  "for" loop vs. "while" loop and the superfluous shift operation 

message: I would like to change the grayToBinary code example to the following.  Reasons: the last iteration of the loop in the existing example is pointlessly taking the exclusive or of num with a mask of zero (except that it doesn't do this when num is zero because there is no looping).  Additionally, conceptually there is no reason that the mask should ever be equal to num; the first reasonable mask is .
/*
 * This function converts a reflected binary
 * Gray code number to a binary number.
 * Each Gray code bit is exclusive-ored with all
 * more significant bits.
 */
unsigned int grayToBinary(unsigned int num)
{
    unsigned int mask = num >> 1;
    while (mask != 0)
    {
        num = num ^ mask;
        mask = mask >> 1;
    }
    return num;
}
Comments?  64.132.59.226 (talk) 13:15, 10 November 2017 (UTC)
thread_title:  Superfluous exclusive or in grayToBinary code example 

message: The example photographic image of an opened Gray code absolute encoder looks like it is actually a plain binary encoder. That should be clear seeing the rotational patterns, that describe binary trees of reflective material. -- Lmatteini (talk) 10:05, 9 November 2018 (UTC)
replies: text: To me it looks like a gray code. Note how, where one circle change from 0 to 1 or 1 to 0, neither of the neighbouring cirlces change at the same position. Their changes are staggered.--Nø (talk) 12:12, 9 November 2018 (UTC)
thread_title:  Example image 

message: After being informed by MrOllie about a potential conflict of interest, I am now formally requesting to make the following additions to the page.
The Combinatorial Object Server is a collection of open source software tools I frequently use to create this kind of illustrations illustrations, and to which I am a frequent contributor.
Two of the papers cited in the following paragraphs were (co)-authored by me.
A: Add the following paragraph to the Section "Constructing an n-bit Gray code":
----
There is an equivalent and conceptually much simpler definition of the binary reflected Gray code via the following greedy algorithm:
We initialize the algorithm with the all-0 string of length n.
Now we repeatedly flip the rightmost (least significant) bit, such that in each step, a new binary string is created that has not been encountered in the list of strings before.
For example, in the case n=3 we start with 000, then we flip the rightmost bit and get 001.
We then flip the middle bit, as flipping the rightmost bit would yield again 000, which we have seen before, yielding 011, etc.
Unlike the previous descriptions, the greedy rule does not directly translate into an efficient algorithm, as it requires storing an exponentially long list of strings and therefore potentially expensive lookup operations.
----
B: Add the following section entitled "Restricting the weight range" before the Section "Special types of Gray codes":
----
We define the weight of a binary string as the number of 1s in the string.
The n-bit BRGC has the surprising property that if we consider the subsequence of strings whose weight is in any fixed interval [k,l], where 0\leq k\leq l\leq n, then any two consecutive strings in this subsequence differ in either 1 bit or 2 bits (in the case of distance 2, the difference is an exchange of a 0 with a 1)
.
This distance property even holds for the difference between the first and last string in the subsequence.
In particular, by restricting the weight range to a single number, i.e., by choosing k=l, we get a cyclic distance-2 Gray code for k-combinations of an n-element set.
This is illustrated in the figure on the right for the case n=5 and four different weight intervals [k,l].
----
C: Revise the following paragraph in the section on "Monotonic Gray codes":
----
Monotonic codes have an interesting connection to a conjecture of Lovász, which asserts that every connected vertex-transitive graph contains a Hamiltonian path. The "middle-level" subgraph Q_{2n+1}(n) is vertex-transitive (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 preceding construction for monotonic codes ensures a Hamiltonian path of length at least 0.839N where \textstyle N=2\binom{2n+1}{n} is the number of vertices in the middle-level subgraph (see also ).
This construction was later improved by Johnson to cycles of length (1-o(1))N, and solved full in full generality by constructing cycles of length N for all n\geq 1 by Mütze. The figure on the right shows a solution for n=3.
----
D: Add the following section entitled "Generalizations" at the very end:
----
The term combinatorial Gray code refers more generally to any listing of combinatorial objects with the property that any two consecutive objects differ in a specified, usually small, way.
For instance, the classical reflected binary code described before is a listing of binary strings of a certain length such that any two consecutive strings differ only in a single bit.
The Steinhaus-Johnson-Trotter algorithm generates a listing of all permutations of a certain length such that any two consecutive permutations differ only in an adjacent transposition.
Another classical combinatorial Gray code is a listing of all binary trees on a certain number of nodes such that any two consecutive trees differ only in a tree rotation.
As a last example, it is possible to list of spanning trees of a graph such that any two consecutive trees differ only in exchanging a single edge.
All of these algorithms are described in Knuth's book.
Any such combinatorial Gray code problem can be rephrased as a Hamiltonian path problem in a suitably defined graph, by taking the combinatorial objects as vertices, and connecting any two that differ in the specified way by an edge. The resulting graph is called a flip graph. Clearly, the question for a Gray code listing of the objects is equivalent to asking for a Hamiltonian path in the flip graph. For the first three combinatorial Gray codes mentioned before, these graphs are the hypercube (binary strings), the permutohedron (permutations), and the associahedron (binary trees).
----
E: Add the following external link:
----
* Generation algorithms for the binary reflected Gray code on the Combinatorial Object Server
----
Torsten Mütze (talk) 16:18, 29 May 2019 (UTC)
replies: text: Hi, thank you very much for the request. Without commenting on the suggested content, I object to the addition of the external link (part "E"), and have removed your remaining three additions of it on the German Wikipedia. An administrator had already undone the fourth (:de:Special:Diff/186098511). Unless Combinatorial Object Server has an article, the external link does not appear to be a relevant addition; due to the number of links added, it rather looks like advertising. ~ ToBeFree (talk) 23:31, 30 May 2019 (UTC)

text: See also: Bottom of Talk:Permutation (Special:PermanentLink/899577378#tbf-objection-2019). ~ ToBeFree (talk) 23:55, 30 May 2019 (UTC)

text: Yes, in particular for restricting the weight range, and for generating the diagrams and wheels. Torsten Mütze (talk) 17:07, 11 June 2019 (UTC)

text: It looks like these requests were fulfilled by  in late May 2019 - a month before you wrote this reply. ~Kvng (talk) 13:40, 2 July 2019 (UTC)
replies: text: Thanks for pointing out that the COI requestor added his own stuff; I reverted it, since it lack supports where.  It was an awful lot of text on an obscure offshoot not discussed in secondary sources.  Any editor is free to put back portions of this material as they see fit. Dicklyon (talk) 13:57, 2 July 2019 (UTC)
thread_title:  Edit request 

message: * The above edit request has not received any non-COI editor responses in the past  weeks (17 days total). 
* The Gray code article is highly technical in nature. Articles such as this may be adversely affected by changes which do not carry the benefit of local editor input and expertise. To that end, a request for input was listed approximately 27 days ago at the talk pages of the WikiProjects which govern this article. No replies were received. 
* Without this additional input, as a safeguard the request has been declined as needing discussion.
* The COI editor is urged to revive stalled communications by making contact with local editors through their own talk pages, then by moving the discussion to this talk page.
* Unless being assisted by another review editor, the COI editor is asked to allow for a reasonable amount of time to pass before reactivating a subsequent  template covering the same request.
Regards,  Spintendo  19:25, 25 June 2019 (UTC)
replies: text: It looks like these requests were fulfilled by  in late May 2019 - a month before you wrote this reply. ~Kvng (talk) 13:40, 2 July 2019 (UTC)
replies: text: Thanks for pointing out that the COI requestor added his own stuff; I reverted it, since it lack supports where.  It was an awful lot of text on an obscure offshoot not discussed in secondary sources.  Any editor is free to put back portions of this material as they see fit. Dicklyon (talk) 13:57, 2 July 2019 (UTC)
thread_title: Reply 25-JUN-2019