BitWhackingGrayCode.java


Below is the syntax highlighted version of BitWhackingGrayCode.java from §6.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++) {
            StdOut.println(Integer.toBinaryString(binaryToGray(i)));
        }
    }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:32:25 EDT 2022.