Possible Duplicate:
Gray code in .NET
I want to get Gray code of a number from its Decimal equivalent.
Example:
Dec Gray Binary
0 000 000
1 001 001
2 011 010
3 010 011
4 110 100
5 111 101
6 101 110
7 100 111
Assuming you only want to do this on non-negative integers:
static uint BinaryToGray(uint num)
{
return (num>>1) ^ num;
}
You might also like to read this blog post which provides methods for conversions in both directions, though the author chose to represent the code as an array of int
containing either one or zero at each position. Personally I would think a BitArray
might be a better choice.