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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With