Bit Manipulation Gray Code Sequence (Java)

Generate a Gray code sequence of n bits in Java using bit manipulation where consecutive values differ by one bit.

JavaData Integrity

Code

javasnippet
10 lines
import java.util.*;
public class GrayCode {
    public static List<Integer> generate(int n) {
        int count = 1 << n;
        List<Integer> result = new ArrayList<>(count);
        for (int i = 0; i < count; i++) result.add(i ^ (i >>> 1));
        return result;
    }
    public static int popcount(int x) { x = x - ((x >>> 1) & 0x55555555); x = (x & 0x33333333) + ((x >>> 2) & 0x33333333); x = (x + (x >>> 4)) & 0x0f0f0f0f; return (x * 0x01010101) >>> 24; }
}

What the code does

Bit Manipulation Gray Code Sequence (Java) reduces to the class GrayCode and the functions generate and popcount.

Repetition is confined to for (int i = 0; i < count; i++) result.add(i ^ (i >>> 1)); — the rest of the file is straight-line.

Applying it

The main signature reads public static List<Integer> generate(int n)

Statements that matter

for (int i = 0; i < count; i++) result.add(i ^ (i >>> 1));
List<Integer> result = new ArrayList<>(count);
int count = 1 << n;

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `generate`, `popcount` at load time.