加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

为什么字节转换不一致golang?

发布时间:2020-12-16 09:25:48 所属栏目:大数据 来源:网络整理
导读:我有以下示例,取自Addison-Wesley Golang一书,我稍作修改: package mainimport "fmt"// pc[i] is the population count of i.var pc [256]bytefunc init() { for i := range pc { pc[i] = pc[i/2] + byte(i1) }}// PopCount returns the population count (
我有以下示例,取自Addison-Wesley Golang一书,我稍作修改:

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

这是操场上的相同代码:example-code
如果链接过期,这里是操场,您可以粘贴上面的内容并播放:go playground

如果你取消注释

// fmt.Println(byte(256>>(0*8)))

你收到一个错误:

prog.go:31: constant 256 overflows byte

鉴于这是在PopCount中完成而不会爆炸,我不明白发生了什么.当有人在主要但不是在PopCount函数中执行此操作时,有人可以帮助解释为什么它会爆炸吗?

我敢说我错过了一些明显的东西!

解决方法

这是因为256>>(0 * 8)(相当于256),是一个无类型常量,它太大而不适合一个字节 language spec状态中的规则

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.

在PopCount函数中,256值的类型为uint64,可以将其转换为字节,将其截断为0.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读