dongshan0202405 2016-06-09 17:37
浏览 94
已采纳

为什么字节转换会不一致地炸毁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
", 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!

  • 写回答

1条回答 默认 最新

  • douhao2026 2016-06-09 17:45
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!