/* * gray_code.c * * Author: Matt Dorsett * * This program calculates gray codes for [0,15] and prints out the absolute difference * between each successive code. Notice that the differences are all powers of 2 (i.e. * just one bit is changing). */ #include int calc_gray_code(int n); int main(int argc, char **argv) { int old_g = 0; int new_g = 0; for (int i = 0; i < 16; i++) { new_g = calc_gray_code(i); int diff = old_g > new_g ? old_g - new_g : new_g - old_g; printf("Gray code of 0x%X is 0x%X, absolute difference is %d\n", i, new_g, diff); old_g = new_g; } } /* Returns the gray encoding of n */ int calc_gray_code(int n) { return (n >> 1) ^ n; }