uint BinaryToGray(uint num)
{
return num ^ (num >> 1); // The operator >> is shift right. The operator ^ is exclusive or.
}
Why does this work?
uint BinaryToGray(uint num)
{
return num ^ (num >> 1); // The operator >> is shift right. The operator ^ is exclusive or.
}
Why does this work?
The wikipedia page for Gray Codes, in the section on Constructing an n-bit code, says:
And then a few paragraphs further down, the same C function is shown.
Consider what is happening on a bitwise level when this expression is evaluated, for a 16 bit number to keep it shorter,
Each bit is being compared to the next higher bit and set if they differ, cleared if they are the same. This follows from the definitions listed earlier on the page.