位移计算结果的差异

huangapple go评论84阅读模式
英文:

Discrepancy in Bitwise Shift Calculation Results

问题

我遇到了一个问题,我的Go程序的输出存在差异,具体涉及到变量x1和x2。以下是相关的代码片段:

package main

var n uint = 10
const N uint = 10

func main() {
    var x1 byte = (1 << n) / 100
    var x2 byte = (1 << N) / 100
    println(x1, x2)
}

期望输出:
10 10

实际输出:
0 10

我想知道这个差异背后的原因,希望能够解释一下。

英文:

I'm encountering a discrepancy in the output of my Go program, specifically with the variables x1 and x2. Here's the relevant code snippet:

package main

var n uint = 10
const N uint = 10

func main() {
    var x1 byte = (1 &lt;&lt; n) / 100
    var x2 byte = (1 &lt;&lt; N) / 100
    println(x1, x2)
}

Expected output:
10 10

Actual Output:
0 10

Curious about the reasoning behind the difference, seeking explanation.

答案1

得分: 1

常量表达式的计算精度是未指定的。在对x2进行赋值的过程中,所有的内容都是常量,因此它正确地计算了2的10次方除以100的结果,即2^10 / 100 = 1024 / 100 = 10。而在第一个表达式中,1被视为一个byte,这意味着它立即被移出。这个1必须被视为一个byte,在规范中有说明:

如果非常量移位表达式的左操作数是一个无类型常量,那么它首先会被隐式转换为它在移位表达式被其左操作数替换时所假设的类型。

这里的左操作数是1,它是一个无类型常量,而n是一个变量,使得表达式变为非常量,因此1必须具有其赋值对象x1的类型,即byte类型。

英文:

Constant expressions get evaluated with unspecified precision. Everything in the assignment to x2 is constant so it's properly calculating 2<sup>10</sup> / 100 = 1024 / 100 = 10. Whereas in the first expression the 1 is treated as a byte, meaning it just gets shifted out immediately. That the 1 must get treated as a byte is in the spec:

> If the left operand of a non-constant shift expression is an untyped constant, it is first implicitly converted to the type it would assume if the shift expression were replaced by its left operand alone.

1 is the untyped constant on the left here, and n being var makes the expression non-constant, so that 1 has to have the type of its assignee x1, i.e. byte.

huangapple
  • 本文由 发表于 2023年6月30日 23:06:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76590151.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定