Hier finden sich C-Routinen zur Umwandlung von Graycode nach Binärcode und umgekehrt. Das Ganze basiert auf dem VHDL-Code hier: Graycode-Umwandlung in VHDL
/*
The purpose of this function is to convert an unsigned
binary number to reflected binary Gray code.
Binary 1-x-0-x-1-x-0-x-1
| ` ` ` `
| | | | | x = xor
v v v v v Abarbeitung MSB ... LSB
Gray 1 1 0 0 1
*/
unsigned short BinaryToGray(unsigned short num)
{
return (num>>1) ^ num;
}
/*
A tricky trick: for up to 2^n bits, you can convert Gray to binary by
performing (2^n) - 1 binary-to Gray conversions. All you need is the
function above and a 'for' loop.
*/
unsigned short GrayToBinary(unsigned short num)
{
int i;
unsigned short temp = num;
for (i=0; i<15; i++) temp = BinaryToGray(temp);
return temp;
}
/*
Gray 1 0 1 0 1
| / / / /
| x x x x x = xor
v/ `v/ `v/ `v/ `v Abarbeitung MSB ... LSB
Binary 1 1 0 0 1
*/
unsigned short GrayToBinaryX(unsigned short num)
{
int i;
unsigned short temp = num;
temp &= 0x8000;
for (i=14; i>=0; i--) {
if ( (!!(temp&(1<<(i+1)))) != (!!(num&(1<<i))) )
temp |= (1<<i);
}
return temp;
}
/*
The purpose of this function is to convert a reflected binary
Gray code number to a binary number.
*/
unsigned short GrayToBinaryPow2(unsigned short num)
{
unsigned short temp = num;
temp ^= (temp>>8);
temp ^= (temp>>4);
temp ^= (temp>>2);
temp ^= (temp>>1);
return temp;
}
Die Grundlagen dieser Umwandlungsroutinen sind auf www.wisc-online.com schön erklärt.