英文:
Why does Go have a "bit clear (AND NOT)" operator?
问题
为什么Go语言有&^
运算符,即"位清除(AND NOT)"运算符?
a &^ b
和a & ^b
之间有什么区别吗?
英文:
Why does Go have &^
, the "bit clear (AND NOT)" operator?
Is there ever any difference between a &^ b
and a & ^b
?
答案1
得分: 14
有一个微妙的区别,使用显式位清除运算符处理字面值和无类型常量会更容易。
无类型整数的默认类型是int,所以像a := uint32(1) & ^1
这样的表达式是非法的,因为^1会先被计算,它被计算为^int(1),结果为-2。然而,a := uint32(1) &^ 1
是合法的,因为这里的1会根据上下文被计算为uint32类型。
使用显式位清除可能还会带来一些性能上的提升,但我对此不太确定。
英文:
There's a subtle difference that makes dealing with literals and untyped constants easier with the explicit bit clear operator.
Untyped integers have their default type as int so something like a := uint32(1) & ^1
is illegal as ^1 is evaluated first and it's evaluated as ^int(1), which equals -2. a := uint32(1) &^ 1
is legal however as here 1 is evaluated as uint32, based on the context.
There could also be some performance gains in having an explicit bit clear, but I'm not too sure about that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论