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 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格