What is the "&^" operator in golang?
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
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.