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
}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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.