Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "&^" operator in golang?

Tags:

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).

like image 333
mosmo Avatar asked Dec 25 '15 02:12

mosmo


2 Answers

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.

like image 98
James Henstridge Avatar answered Nov 02 '22 13:11

James Henstridge


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

like image 24
Sheila Wendler Avatar answered Nov 02 '22 15:11

Sheila Wendler