为什么Go语言有一个”位清除(AND NOT)”运算符?

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

Why does Go have a "bit clear (AND NOT)" operator?

问题

为什么Go语言有&^运算符,即"位清除(AND NOT)"运算符?

a &^ ba & ^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.

huangapple
  • 本文由 发表于 2017年5月4日 19:53:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/43782187.html
匿名

发表评论

匿名网友

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

确定