英文:
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 "fmt"
func main(){
var x uint8 = 1
var y uint8 = 1 << 2
fmt.Printf("%08b\n", x &^ y);
}
Result:
> 00000001
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论