移位和逻辑运算给出了意外的答案

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

Shift and Logical operation giving unexpected answer

问题

func main() {
	var score int = 5
	var shifter int = 3

	if score&1<<shifter != 0 {
		fmt.Println(score, 1<<shifter, score&1<<shifter)
	} else {
		fmt.Println("false")
	}
}

我预期 5 & 8 应该是 0,但是在按位与运算后,我看到的答案是 8。我做错了什么?据我所知,<< 在整数类型上运算应该给我 0。

英文:
func main() {
	var score int = 5
	var shifter int = 3

	if score&amp;1&lt;&lt;shifter != 0 {
		fmt.Println(score, 1&lt;&lt;shifter, score&amp;1&lt;&lt;shifter)
	} else {
		fmt.Println(&quot;false&quot;)
	}
}

I'm expecting a 5 & 8 should be 0 but instead I'm seeing 8 as the answer after bitwise AND. What am I doing wrong? AFAICT, << is operating on integer types and should give me 0.

答案1

得分: 4

运算符<<&具有相同的优先级,所以你实际上正在做的是:

(score&1)<<shifter

看起来你需要的是:

score&(1<<shifter)
英文:

The operator &lt;&lt; and &amp; has the same precedence, so what you are actually doing is:

(score&amp;1)&lt;&lt;shifter

Looks like what you need is:

score&amp;(1&lt;&lt;shifter)

huangapple
  • 本文由 发表于 2021年6月17日 02:50:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/68008478.html
匿名

发表评论

匿名网友

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

确定