What is the "&^" operator in golang?

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

What is the "&^" operator in golang?

问题

我无法真正使用"AND NOT"进行谷歌搜索并获得任何有用的结果,这个运算符到底是什么,我该如何在像C语言这样的语言中实现它?我查看了规范,但里面没有什么有用的信息,只有一个列表,上面写着&^(AND NOT)。

英文:

I can't really google the name AND NOT and get any useful results, what exactly is this operator, and how could I do this in a language like C? I checked the specification, and there is nothing helpful in there but a list that says it's &^ (AND NOT).

答案1

得分: 56

Go表达式x &^ y的C等效表达式只是x & ~y。这实际上是“x与(y的按位取反)”的意思。

规范的算术运算符部分中,描述了&^作为“位清除”操作,这给出了你想要使用它的一个想法。作为两个单独的操作,~y将每个位转换为零,然后清除x中对应的位。每个零位将被转换为一,这将保留x中对应的位。

因此,如果你将x | y视为根据掩码常量y打开x的特定位的方法,那么x &^ y则相反,关闭那些相同的位。

英文:

The C equivalent of the Go expression x &^ y is just x & ~y. That is literally "x AND (bitwise NOT of y)".

In the arithmetic operators section of the spec describes &^ as a "bit clear" operation, which gives an idea of what you'd want to use it for. As two separate operations, ~y will convert each one bit to a zero, which will then clear the corresponding bit in x. Each zero bit will be converted to a one, which will preserve the corresponding bit in x.

So if you think of x | y as a way to turn on certain bits of x based on a mask constant y, then x &^ y is doing the opposite and turns those same bits off.

答案2

得分: 6

> &^ 运算符是位清除(AND NOT)运算符:在表达式 z = x &^ y 中,如果 y 的对应位为 1,则 z 的对应位为 0;否则,z 的对应位等于 x 的对应位。

来自《The Go Programming Language》

示例:

package main
import "fmt"

func main(){
    var x uint8 = 1
    var y uint8 = 1 << 2

    fmt.Printf("%08b\n", x &^ y);

}  

结果:
> 00000001

英文:

> The &^ operator is bit clear (AND NOT): in the expression z = x &^ y,
> each bit of z is 0 if the corresponding bit of y is 1; otherwise it
> equals the corresponding bit of x.

From The Go Programming Language

Example:

package main
import &quot;fmt&quot;

func main(){
    var x uint8 = 1
    var y uint8 = 1 &lt;&lt; 2

    fmt.Printf(&quot;%08b\n&quot;, x &amp;^ y);

}  

Result:
> 00000001

huangapple
  • 本文由 发表于 2015年12月25日 10:10:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/34459450.html
匿名

发表评论

匿名网友

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

确定