Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does byte cast blow up inconsistently golang?

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\n", x)
    fmt.Printf("byte(%d>>(0*8)) is %d\n", 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!

like image 392
Jake_Howard Avatar asked Jun 09 '16 17:06

Jake_Howard


1 Answers

The is because 256>>(0*8) (equivalent to 256), is an untyped constant, which is too large to fit in a byte The rules in the language spec state

A constant value x can be converted to type T in any of these cases:

  • x is representable by a value of type T.
  • x is a floating-point constant, T is a floating-point type, and x is representable by a value of type T after rounding using IEEE 754 round-to-even rules, but with an IEEE -0.0 further rounded to an unsigned 0.0. The constant T(x) is the rounded value.
  • x is an integer constant and T is a string type. The same rule as for non-constant x applies in this case.

Inside your PopCount function, the 256 value is of type uint64, which can be converted to a byte, truncating it to 0.

like image 147
JimB Avatar answered Nov 19 '22 02:11

JimB