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(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))}
这是 *** 场上的相同代码: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.
总结以上是内存溢出为你收集整理的为什么字节转换不一致golang?全部内容,希望文章能够帮你解决为什么字节转换不一致golang?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)