英文:
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&1<<shifter != 0 {
fmt.Println(score, 1<<shifter, score&1<<shifter)
} else {
fmt.Println("false")
}
}
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 <<
and &
has the same precedence, so what you are actually doing is:
(score&1)<<shifter
Looks like what you need is:
score&(1<<shifter)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论