I am writing following code to calculate Population Count as below:
package main
import (
"fmt"
)
func main() {
var pc [256]byte
for i := range pc {
pc[i] = pc[i/2] + byte(i&1)
}
var x uint64 = 65535
var population uint8
for i := 0; i < 8; i++ {
population = population + pc[byte(x>>(i*8))]
}
fmt.Printf("Population Count: %d", population)
}
On compilation I get following error:
prog.go:19:39: invalid operation: x >> (i * 8) (shift count type int, must be unsigned integer)
The problem is with the variable i
which is declared while initializing the for loop. The shorthand initialization of i
makes it of type int
which in internally of type signed int32
. This is why the following line:
population = population + pc[byte(x>>(i*8))]
is causing the problem. Because shift operator >>
is expecting only unsigned integer, but the expression i*8
results into int
which is internally signed int32
.
As var
can not be used in for
initialization.
for var i uint8 = 0; i < 8; i++ { ... }
syntax error: var declaration not allowed in for initializer
I can declare variable i
outside of for loop
, but I do not find it clean and readable.
What should be the clean way to achieve the same?