Bit Manipulation Gray Code Sequence (Go)

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

GoData Integrity

Code

gosnippet
15 lines
package main

func grayCode(n int) []int {
	count := 1 << n
	result := make([]int, count)
	for i := 0; i < count; i++ { result[i] = i ^ (i >> 1) }
	return result
}

func popcount(x int) int {
	x = x - ((x >> 1) & 0x55555555)
	x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
	x = (x + (x >> 4)) & 0x0f0f0f0f
	return (x * 0x01010101) >> 24
}

How it works

Count the functions grayCode and popcount as the entire surface area of Bit Manipulation Gray Code Sequence (Go).

One loop does the cycling here: for i := 0; i < count; i++ { result[i] = i ^ (i >> 1) }.

What to watch for

  • The whole dependency story is the language version itself.

Applying it

Entry signature: func grayCode(n int) []int

Statements that matter

func grayCode(n int) []int {
count := 1 << n
result := make([]int, count)
for i := 0; i < count; i++ { result[i] = i ^ (i >> 1) }
return result
}
func popcount(x int) int {
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
return (x * 0x01010101) >> 24
}

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `grayCode`, `popcount` at load time.