Bit Manipulation Gray Code Sequence (JavaScript)
Generate a Gray code sequence of n bits using bit manipulation where consecutive values differ by exactly one bit.
Code
function grayCode(n) {
const result = [];
const count = 1 << n;
for (let i = 0; i < count; i++) result.push(i ^ (i >>> 1));
return result;
}
function grayToBinary(gray) {
let bin = gray;
while (gray >>> 1) { gray >>>= 1; bin ^= gray; }
return bin;
}
function popcount(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 (JavaScript) keeps everything in the functions grayCode, grayToBinary and popcount.
Iteration is nested: for (let i = 0; i < count; i++) result.push(i ^ (i >>> 1)); frames the pass, while (gray >>> 1) { gray >>>= 1; bin ^= gray; } does the per-item step.
Using it
The primary signature is function grayCode(n)
Key statements
return (x * 0x01010101) >>> 24;
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `grayCode`, `grayToBinary`, `popcount` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.