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.

JavascriptData Integrity

Code

snippet
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;
}