Jump to content

Talk:Gray code: Difference between revisions

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia
Content deleted Content added
→‎Gray code code example changes: Working with the formulation of Glrx.
Line 463: Line 463:
{{outdent}}
{{outdent}}
:There were no concrete proposals to edit the page; the three statements were general. I do not see that any response was required. Furthermore, 64.132 has not achieved consensus before; trying to wear down the opposition is not a good tactic. Moreover, consensus is not compromise. Editorial decisions are not trying to make everybody happy. "There is currently a disagreement as to whether specifying when the code/algorithm terminates is a coding detail or an essential part of the algorithm" completely misstates the disagreement. There is no doubt that <code>grayToBinary32</code> terminates. There is no doubt that it is restricted to codes that are 32 bits or less. As Andy stated, most Gray code applications will be fewer than 16 bits. [[User:Glrx|Glrx]] ([[User talk:Glrx|talk]]) 20:03, 5 October 2017 (UTC)
:There were no concrete proposals to edit the page; the three statements were general. I do not see that any response was required. Furthermore, 64.132 has not achieved consensus before; trying to wear down the opposition is not a good tactic. Moreover, consensus is not compromise. Editorial decisions are not trying to make everybody happy. "There is currently a disagreement as to whether specifying when the code/algorithm terminates is a coding detail or an essential part of the algorithm" completely misstates the disagreement. There is no doubt that <code>grayToBinary32</code> terminates. There is no doubt that it is restricted to codes that are 32 bits or less. As Andy stated, most Gray code applications will be fewer than 16 bits. [[User:Glrx|Glrx]] ([[User talk:Glrx|talk]]) 20:03, 5 October 2017 (UTC)

::A downside of using an IP address is that it changes when I move to a different location. To head off any accusations of [[WP:SOCK|sock puppetry]], I hereby report that I am one and the same as 64.132.59.226.

::Thank you, @[[User:Glrx|Glrx]] for discussing the merits of the changes to the article. I acknowledge that you do not like the way I have formulated the disagreement and I will try to work with your formulation. I am not expert at quantifying how many people would want a Gray code of more than 32 bits for some purpose. However, I am hopeful that we would agree that it is an easy win to support such larger Gray codes ''if'' it outweighs any downside. I hope that I am remaining consistent with your formulation if I make a concrete proposal with the intent to minimize such a downside.

::I would accommodate these large Gray codes with a few words in the comment without changing the program itself. I would not modify the existing sentence in the comment. I propose a new second sentence, "For Gray codes of N&nbsp;>&nbsp;32 bits, have the bit shift amounts be the powers of two with value strictly less than N". I see this as minimally impacting the existing strong points of the present article. I see it as a fundamental truism of the algorithm, independent of coding decisions such as C vs. Java vs. Python. As a bonus, it promotes independence from code-dependent values such as sizeof(some type). [[Special:Contributions/74.76.180.38|74.76.180.38]] ([[User talk:74.76.180.38|talk]]) 20:05, 6 October 2017 (UTC)

Revision as of 20:07, 6 October 2017

WikiProject iconComputing C‑class
WikiProject iconThis article is within the scope of WikiProject Computing, a collaborative effort to improve the coverage of computers, computing, and information technology on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.
CThis article has been rated as C-class on Wikipedia's content assessment scale.
???This article has not yet received a rating on the project's importance scale.
WikiProject iconMathematics C‑class Low‑priority
WikiProject iconThis article is within the scope of WikiProject Mathematics, a collaborative effort to improve the coverage of mathematics on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.
CThis article has been rated as C-class on Wikipedia's content assessment scale.
LowThis article has been rated as Low-priority on the project's priority scale.

Animation

The rotary encode and, in particular, the STGC images would benefit enormously from animation! Casual viewers could miss the magic of this concept: making paper versions to explain this to my children was time-consuming and probably less clear than an animation could be. —Preceding unsigned comment added by 81.108.210.118 (talk) 09:49, 8 October 2009 (UTC)[reply]

Animated and color-coded STGC rotor.

I have completed an animation based on the svg shown. I agreed that the static image and the discussion were obscuring the functional beauty of STGC. While my image works it may be too colorful for some tastes

The original svg and discussion did not identify the sensors, define when the sensor would switch from on to off and did not even define whether the slots or sensors would be spinning and in which direction the spin would occur. These facts made correlating the chart with the svg difficult.

Note: I discovered that the three slots are at (0, 120) (168, 204) (228, 252), and that the 5 sensors start at 0 degrees and are evenly distributed around the circle with a separation of 72 degrees. The slots rotate as this would most accurately mimic a physical device. The direction of clock-wise rotation and the identity of the sensors (red, purple, yellow, blue and green) were chosen to match the bit-patterns displayed in the Greycode article.

Preceding comment added by Perlygatekeeper (talkcontribs) 18:14, 9 June 2017 (UTC)[reply]

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)[reply]

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)[reply]

Code snippets

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)[reply]

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)[reply]

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)[reply]

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)[reply]
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)[reply]
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)[reply]

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)[reply]

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)[reply]

Anti-Gray Codes?

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)[reply]

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)[reply]

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)[reply]


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).

haskell code?

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)[reply]

  • 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 (talkcontribs) 04:30, 3 January 2009 (UTC)[reply]

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 (talkcontribs) 07:29, 25 September 2008 (UTC)[reply]

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)[reply]
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)[reply]

Algorithm correct?

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)[reply]

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)[reply]

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)[reply]

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)[reply]

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)[reply]

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)[reply]

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)[reply]

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)[reply]

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)[reply]

Iterative construction cleanup.

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 - 1k ≤ 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)[reply]

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)[reply]
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)[reply]

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[reply]

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)[reply]

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)[reply]

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)[reply]

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)[reply]

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)[reply]
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)[reply]

Fast conversion to binary

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)[reply]

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

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)[reply]

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)[reply]

Yes, much better. I'd style it nicer and use int though: Dicklyon (talk) 15:54, 4 November 2011 (UTC)[reply]
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.

-- Elphion (talk) 06:49, 15 April 2013 (UTC)[reply]

Baudot code, one of the first use of Gray code

In article page, Baudot code might be given as historically it was one of the first use of gray code, has shown by next illustration:

Illustration: Baudot code

Let ·Fig. · V · IV·   · I · II·III·
----+-----+---+---+---+---+---+---+
 A  · 1   ·   ·   ·   · ● ·   ·   ·    
É / · 1/  ·   ·   ·   · ● · ● ·   ·    
 E  · 2   ·   ·   ·   ·   · ● ·   ·    
 I  · 3/  ·   ·   ·   ·   · ● · ● ·    
 O  · 5   ·   ·   ·   · ● · ● · ● ·    
 U  · 4   ·   ·   ·   · ● ·   · ● ·    
 Y  · 3   ·   ·   ·   ·   ·   · ● ·    
 
 B  · 8   ·   · ● ·   ·   ·   · ● ·    
 C  · 9   ·   · ● ·   · ● ·   · ● ·    
 D  · 0   ·   · ● ·   · ● · ● · ● ·    
 F  · 5/  ·   · ● ·   ·   · ● · ● ·    
 G  · 7   ·   · ● ·   ·   · ● ·   ·    
 H  · ¹   ·   · ● ·   · ● · ● ·   ·    
 J  · 6   ·   · ● ·   · ● ·   ·   ·    
 Fig. Bl. ·   · ● ·   ·   ·   ·   ·    
 *  · *   · ● · ● ·   ·   ·   · 
 K  · (   · ● · ● ·   · ● ·   · 
 L  · =   · ● · ● ·   · ● · ● · 
 M  · )   · ● · ● ·   ·   · ● · 
 N  · £   · ● · ● ·   ·   · ● · ●
 P  · +   · ● · ● ·   · ● · ● · ●
 Q  · /   · ● · ● ·   · ● ·   · ●
 R  · –   · ● · ● ·   ·   ·   · ●
 S  · 7/  · ● ·   ·   ·   ·   · ●
 T  · ²   · ● ·   ·   · ● ·   · ●
 V  · ¹   · ● ·   ·   · ● · ● · ●
 W  ·  ?  · ● ·   ·   ·   · ● · ●
 X  · 9/  · ● ·   ·   ·   · ● · 
 Z  ·  :  · ● ·   ·   · ● · ● · 
 –  · .   · ● ·   ·   · ● ·   · 
 Let. Bl. · ● ·   ·   ·   ·   ·   ·  

— Preceding unsigned comment added by 86.67.203.56 (talk) 15:47, 29 June 2014 (UTC)[reply]

  • Comment. I am lost here. Baudot may have used a Gray code for the character assignments, but there does not seem to be any advantage in what is an arbitrary assignment. Where is the encoder-style problem? If I need to send a Q, then being off by 1 bit is an error. I'd remove the reference to Baudot being a Gray code. Glrx (talk) 00:57, 4 July 2014 (UTC)[reply]
Here I found a description on how the Baudot system was working:
original version english version
Le combinateur qui est la cheville ouvrière du système se compose de cinq disques à rayon tantôt métallique tantôt isolant, sur lesquels se meut un frotteur, armé de cinq ressorts, qui tourne synchroniquement (...).

Les armatures (...) forment (...) une genre de commutateur d'un genre particulier qui ouvre une issue au courant local chargé de produire l'impression, au moment précis où la caractère transmis passe en regard du papier.[1]

The combinateur which is the main working part of the system is made of five disks à rayon one time metallic, one time non metallic, on which move a frotteur, armed with five ressorts, which turn simultaneously (...).

The armatures (...) makes (...) some kind of commutateur from a new specific kind which open one way to local electricity which role is to produce the printing, at the accurate time when the transmitted character is in regard (in front) of the paper.

From my understanding, if you use a code different of the gray one, you might encounter some intermediate values while the disk is turning between two characters which might print something you do not want? — Preceding unsigned comment added by 77.199.96.122 (talk) 23:08, 6 September 2016 (UTC)[reply]
Baudot's equipment did not have transition problems because it was synchronous. The operator would hear a click and then press the next code chord. The keys would lock down until the commutator released them. The character assignments are essentially arbitrary, but Baudot apparently made some effort to minimize operator fatigue: vowels did not use the left hand keys.
For Wikipedia's purpose, we would need a reliable reference that says Baudot was a Gray code. I doubt there is such a reference. Baudot was not trying to solve the measurement uncertainty issue, so it seems that Baudot may have done a gray-like sequencing, but that may be because he did not think of a binary code assignment. Also, the gray sequence above had to insert the FIGS shift in the middle of the consonants and the digits are not in numerical order. Some assignments look simple and obvious: the infrequent FIGS and LTRS codes are one left finger assignments with repeats in that shift block being blank.
Glrx (talk) 18:31, 11 September 2016 (UTC)[reply]

References

  1. ^ cnum.cnam.fr/CGI/fpage.cgi?8XAE277-11.2/35/100/74/0/0

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)[reply]

Yes; but what subsection do you have in mind? Dicklyon (talk) 03:45, 13 December 2014 (UTC)[reply]

Gray code code example changes

Please look again at my edit to the Gray code article, which you undid. My provided code re-write still makes use of doubling the shift at each step, just like the replaced code. I think that is the point you refer to in your edit comment. My edit just reverses the order of the XORs, which is legitimate, and puts them in a loop that self-detects when it can stop. Thank you -- 64.132.59.226 (talk) 16:28, 14 September 2017 (UTC)[reply]

Read the edit summary, "rv - missing the point of that whole example."
Your change is both unencyclopedic, and it misses the point of that whole example. This is not a coding cookbook of examples, it's not a coding tutorial. We're not looking for good coding here, we're looking for good explanations of Gray code itself. The version without the explicit stated shifts is much clearer for that. There's also a loop-based example immediately preceding it. Andy Dingley (talk) 16:41, 14 September 2017 (UTC)[reply]
Thank you for clarifying which point you are making. However, since your note is brief, I am not completely sure that you understand the point I am making. At the risk of repeating something that is already obvious to you ... my point is that the grayToBinary example uses a loop that shifts one position at time. The grayToBinary32 example (both as originally and as I have edited it) instead doubles the shift each time. To me, that is the defining difference between these two examples, rather than that one is a loop and that the other is an unrolled loop. Unfortunately, the existing grayToBinary32 has a shortfall, in that it assumes sizeof(unsigned int) == 4, which can silently change if code is moved from one computer to another. It was my hope to repair that shortfall. Can you think of an approach that repairs the shortfall while maintaining the clarity you hope to see? Thank you for entertaining my questions and considering my perspective. 64.132.59.226 (talk) 17:04, 14 September 2017 (UTC)[reply]
This is not a coding tutorial. This is an explanation of Gray code. It needs to be the clearest explanation of Gray code that is can be, not the most optimised (for size or run time) code fragment. That alone is reason to keep the original example.
Secondly, this is a Gray code. I've never seen a 32 bit Gray code. I cannot imagine a use for a 32 bit Gray code, at least not out in the physical world of encoders. I once had a very expensive problem where a machine had been fitted with a 7 bit Gray code encoder when it needed a 9 bit encoder. We couldn't afford this (we could, but I was told we couldn't, after wasting far more chasing the problem of using a 7 bit code) and I had to make it work with a 8 bit encoder instead. Now imagine how impossible it would be to rule a grating for a 32 bit Gray code! Two billion increments! Andy Dingley (talk) 17:21, 14 September 2017 (UTC)[reply]
I fear that this discussion will not resolve with agreement. Nonetheless, I wish to note some counterarguments. The one-shift-at-a-time grayToBinary example is not an unrolled loop; do you consider it to be in need of clarification / unrolling, or is it only the doubling-shift approach that needs to remain unrolled? If so, why? Second, people may have a need to convert to a Gray code and back even in situations where they are not enumerating all 232 or larger possibilities. Suppose I want to know the 10100-th position for the 500-level Towers of Hanoi puzzle? Thank you for your time and energy. 64.132.59.226 (talk) 17:34, 14 September 2017 (UTC)[reply]
I modified the comment in the code instead of the code itself. I am hopeful that this is an acceptable compromise. 64.132.59.226 (talk) 13:10, 15 September 2017 (UTC)[reply]
I reverted. There should be a clear point to make. Glrx (talk) 03:46, 20 September 2017 (UTC)[reply]
I fixed the edit to address the submission comment that the focus should be the algorithm not the code. 64.132.59.226 (talk) 13:23, 26 September 2017 (UTC)[reply]
By "fixed" you mean "yet again re-inserted a change that others are clearly against". Andy Dingley (talk) 15:18, 26 September 2017 (UTC)[reply]
@Andy Dingley: I am attempting to find a compromise solution that addresses everyone's priorities. If I have failed, I ask you to please try for a compromise yourself. Straight out reverts are less useful in conveying your priorities, but if you feel that that is your best course of action then I understand, and I will try again. 64.132.59.226 (talk) 11:57, 27 September 2017 (UTC)[reply]
You need to get consensus on this talk page before you reinsert your edits. Do not continually "try again". Propose the change on the talk page and get consensus for it. WP is interested in algorithms. Adding comments about the potential limitations of shift instructions is about programming detail rather than the algorithm. Glrx (talk) 01:59, 28 September 2017 (UTC)[reply]
Yes, please let's try for consensus. Please express your degree of support for the following statements:
  1. As I would characterize it, the fast algorithm for converting a gray code to a number is to use a sequence of exclusive-ors with shifts of the previous intermediate results, and the specification of the algorithm necessarily describes how many of these operations are required.
  2. The current version of the code assumes 32-bit unsigned integers, which I would characterize as a coding assumption, not an algorithm essential.
  3. For reasons of efficiency, we may not want to change the code itself, but we can discuss the removal of the 32-bit coding assumption with a few words in the code comment.
64.132.59.226 (talk) 16:02, 28 September 2017 (UTC)[reply]
It has been a week of discussion and there have been no dissenters. A consensus of one is a consensus, but it is pretty weak. Please post your pros and cons. If you can envision an approach that you believe addresses everyone's priorities, please suggest it! 64.132.59.226 (talk) 11:55, 5 October 2017 (UTC)[reply]
"there have been no dissenters"
Rubbish. This is getting to the point of WP:TENDENTIOUS Andy Dingley (talk) 12:26, 5 October 2017 (UTC)[reply]
Thank you for your correction. I should have said that no one spoke up during the week. Previous to then there were dissenters. I stand corrected.
However, some of that previous dissent was of the form "What's the point?", which was not useful in arriving at consensus. There is currently a disagreement as to whether specifying when the code/algorithm terminates is a coding detail or an essential part of the algorithm. That is the topic for which I have seen no discussion. Please, please address this issue. 64.132.59.226 (talk) 15:47, 5 October 2017 (UTC)[reply]
No. You are the one trying to advocate a change. You have to make a case as to why that is a concrete improvement. If you cannot, or if you can only make "change for change sake", then you don't get to make it. Nor can you play "keep at it for longer than anyone else can be bothered". Your editing on other articles, such as United States customary units are based equally on edit-warring against other editors. Andy Dingley (talk) 16:03, 5 October 2017 (UTC)[reply]
There were no concrete proposals to edit the page; the three statements were general. I do not see that any response was required. Furthermore, 64.132 has not achieved consensus before; trying to wear down the opposition is not a good tactic. Moreover, consensus is not compromise. Editorial decisions are not trying to make everybody happy. "There is currently a disagreement as to whether specifying when the code/algorithm terminates is a coding detail or an essential part of the algorithm" completely misstates the disagreement. There is no doubt that grayToBinary32 terminates. There is no doubt that it is restricted to codes that are 32 bits or less. As Andy stated, most Gray code applications will be fewer than 16 bits. Glrx (talk) 20:03, 5 October 2017 (UTC)[reply]
A downside of using an IP address is that it changes when I move to a different location. To head off any accusations of sock puppetry, I hereby report that I am one and the same as 64.132.59.226.
Thank you, @Glrx for discussing the merits of the changes to the article. I acknowledge that you do not like the way I have formulated the disagreement and I will try to work with your formulation. I am not expert at quantifying how many people would want a Gray code of more than 32 bits for some purpose. However, I am hopeful that we would agree that it is an easy win to support such larger Gray codes if it outweighs any downside. I hope that I am remaining consistent with your formulation if I make a concrete proposal with the intent to minimize such a downside.
I would accommodate these large Gray codes with a few words in the comment without changing the program itself. I would not modify the existing sentence in the comment. I propose a new second sentence, "For Gray codes of N > 32 bits, have the bit shift amounts be the powers of two with value strictly less than N". I see this as minimally impacting the existing strong points of the present article. I see it as a fundamental truism of the algorithm, independent of coding decisions such as C vs. Java vs. Python. As a bonus, it promotes independence from code-dependent values such as sizeof(some type). 74.76.180.38 (talk) 20:05, 6 October 2017 (UTC)[reply]