Saturday, March 17, 2012

Binary To Gray's Code and vice versa.


Write a recursive function to convert Binary Code of a number into its equivalent Gray's code and the other way round.


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

int binaryToGray(unsigned int num) {
        return (num>>1) ^ num;
}


code input/output:
Binary => Gray
000 => 000
001 => 001
010 => 011
011 => 010
100 => 110
101 => 111
110 => 101
111 => 100


Gray => Binary
000 => 000
001 => 001
011 => 010
010 => 011
110 => 100
111 => 101
101 => 110
100 => 111

No comments:

Post a Comment