dongshan0202405 2016-06-09 17:37
浏览 94


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))] +
func main() {
    // fmt.Println(byte(256>>(0*8)))  // This blows up, but doesn't blow up on line 19 or line 20, why?

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.

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



  • ¥15 想编写一个期货跨期套利的程序
  • ¥15 UltraScale 系列 Bitslip 技术支持
  • ¥15 一个线程在sleep的时候set一个信号会起作用吗
  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献