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.
Code
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
}Report a problem with this exampleOpens a pre-filled issue on GitHub.