Home | About | Apps | Github | Rss

Left Shift with Float Conversion in Go!

The following piece of code while it looks innocent actually does not compile

return int64(0.5 * float64((1<<n)-1))

It produces the following error

exp.go:22:28: invalid operation: 1 << n (shift of type float64)

What is happening here?

This is because when you do float64(1<<n) the first instinct of golang’s compiler is to convert the 1 into float64. So its equivalent to float64(1) << n which obviously would not work because you can’t shift floats.

The solution is to rewrite it into two statements

pow2minus1 := (1<<n) - 1
return int64(0.5 * float64(pow2minus1)

More posts