Bit Manipulation Gray Code Sequence Typed
Generate a typed Gray code sequence of n bits where consecutive values differ by exactly one bit.
Code
function grayCode(n: number): number[] {
const result: number[] = [];
const count = 1 << n;
for (let i = 0; i < count; i++) result.push(i ^ (i >>> 1));
return result;
}
function grayToBinary(gray: number): number { let bin = gray; while (gray >>> 1) { gray >>>= 1; bin ^= gray; } return bin; }
function popcount(x: number): number { x = x - ((x >>> 1) & 0x55555555); x = (x & 0x33333333) + ((x >>> 2) & 0x33333333); x = (x + (x >>> 4)) & 0x0f0f0f0f; return (x * 0x01010101) >>> 24; }How the snippet works
Bit Manipulation Gray Code Sequence Typed keeps everything in the functions grayCode, grayToBinary and popcount.
Iteration happens inside for (let i = 0; i < count; i++) result.push(i ^ (i >>> 1)); — everything outside it runs once.
Using it
The primary signature is function grayCode(n: number)
Key statements
function grayToBinary(gray: number): number { let bin = gray; while (gray >>> 1) { gray >>>= 1; bin ^= gray; } return bin; }
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `grayCode`, `grayToBinary`, `popcount` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.