I have the following example, taken from the Addison-Wesley Golang book, which I have modified slightly:
package main
import "fmt"
// pc[i] is the population count of i.
var pc [256]byte
func init() {
for i := range pc {
pc[i] = pc[i/2] + byte(i&1)
}
}
// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
fmt.Printf("Value is %d
", x)
fmt.Printf("byte(%d>>(0*8)) is %d
", x, byte(x>>(0*8)))
y := byte(x>>(0*8))
return int(pc[y] +
pc[byte(x>>(1*8))] +
pc[byte(x>>(2*8))] +
pc[byte(x>>(3*8))] +
pc[byte(x>>(4*8))] +
pc[byte(x>>(5*8))] +
pc[byte(x>>(6*8))] +
pc[byte(x>>(7*8))])
}
func main() {
// fmt.Println(byte(256>>(0*8))) // This blows up, but doesn't blow up on line 19 or line 20, why?
fmt.Println(PopCount(256))
}
Here's the same code in the playground: example-code Just in case the link expires, here's the playground where you can paste the above and play: go playground
If you uncomment
// fmt.Println(byte(256>>(0*8)))
You get an error:
prog.go:31: constant 256 overflows byte
Given this is done inside PopCount without blowing up, I don't understand what's going on. Can someone help explain why it blows up when I do it in main but not in the function PopCount?
I dare say I'm missing something obvious!