Gray code

func bin2gray(n) {
    n ^ (n >> 1)
}
 
func gray2bin(num) {
    var bin = num
    while (num >>= 1) { bin ^= num }
    return bin
}
 
{ |i|
    var gr = bin2gray(i)
    printf("%d\t%b\t%b\t%b\n", i, i, gr, gray2bin(gr))
} << ^32

Output:

0       0       0       0
1       1       1       1
2       10      11      10
3       11      10      11
4       100     110     100
5       101     111     101
6       110     101     110
7       111     100     111
8       1000    1100    1000
9       1001    1101    1001
10      1010    1111    1010
11      1011    1110    1011
12      1100    1010    1100
13      1101    1011    1101
14      1110    1001    1110
15      1111    1000    1111
16      10000   11000   10000
17      10001   11001   10001
18      10010   11011   10010
19      10011   11010   10011
20      10100   11110   10100
21      10101   11111   10101
22      10110   11101   10110
23      10111   11100   10111
24      11000   10100   11000
25      11001   10101   11001
26      11010   10111   11010
27      11011   10110   11011
28      11100   10010   11100
29      11101   10011   11101
30      11110   10001   11110
31      11111   10000   11111

Last updated