BitWhackingGrayCode.java


Below is the syntax highlighted version of BitWhackingGrayCode.java from §5.1 Data Representations.


/*************************************************************************
 *  Compilation:  javac BitWhackingGrayCode.java
 *  Execution:    java BitWhackingGrayCode N
 *  
 *  Print the N-bit binary reflected Gray code using bit-whacking
 *  operations.
 *
 *  % java BitWhackingGrayCode 3
 *  000 
 *  001
 *  011
 *  010
 *  110 
 *  111
 *  101
 *  100
 *
 *************************************************************************/

public class BitWhackingGrayCode {

    // convert integer n to its corresponding gray code alue
    static int binaryToGray(int n) {
        return (n >>> 1) ^ n;
    }

    // in case you want to go the other way around
    static int grayToBinary(int n) {
        for (int i = 16; i > 0; i /= 2) 
            n ^= n >>> i;
        return n;
    }


    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        for (int i = 0; i < Math.pow(2, N); i++)
            System.out.println(Integer.toBinaryString(binaryToGray(i)));
    }

}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Sep 29 16:17:41 EDT 2009.