Matt M
Matt M

Reputation: 53

Usage and meaning of &^ and &^= operators in Go

I've been looking around for about a week now and can't seem to find a decent explanation for these two operators, &^ and &^=, in the Go language and how they are used. Would anybody be as kind as to enlighten me?

Upvotes: 4

Views: 207

Answers (2)

user1820956
user1820956

Reputation:

This is easier to understand when we take a look at all the bitwise operators:

&    bitwise AND
|    bitwise OR
^    bitwise XOR
&^   bit clear (AND NOT)
  1. Bitwise AND (&): Result is 1 when both operand bits are 1, else the result is 0.
  2. Bitwise OR (|): Result is 1 when at least one operand bit is 1, else 0 if both operand bits are 0.
  3. Bitwise XOR (^): Result is 1 when one, and only one operand bit is 1, else the result is 0. These three operators (&, |, ^) produce the same result irrespective of the order of operand bits.
  4. Bitwise AND NOT (&^): Result is 1 when the first operand bit is 1, and the second operand bit is 0; else the result is 0. Note that the order of the operand bit affects the result. For the result to be 1, the first operand bit must be 1 and the second must be 0.

Here's code, also on the Go Playground, that demonstrates the behavior of bitwise operators:

package main

import "fmt"

func main() {
    fmt.Println(`AND`)
    fmt.Printf("%b & %b results in %03b\n", 4, 5, 4&5)
    fmt.Printf("%b & %b results in %03b\n", 5, 4, 5&4)
    fmt.Println(`OR`)
    fmt.Printf("%b | %b results in %03b\n", 4, 5, 4|5)
    fmt.Printf("%b | %b results in %03b\n", 5, 4, 5|4)
    fmt.Println(`XOR`)
    fmt.Printf("%b ^ %b results in %03b\n", 4, 5, 4^5)
    fmt.Printf("%b ^ %b results in %03b\n", 5, 4, 5^4)
    fmt.Println(`AND NOT`)
    fmt.Printf("%b &^ %b results in %03b\n", 7, 5, 7&^5)
    fmt.Printf("%b &^ %b results in %03b\n", 5, 7, 5&^7)
}

The output generated by running the above code is:

AND
100 & 101 results in 100
101 & 100 results in 100
OR
100 | 101 results in 101
101 | 100 results in 101
XOR
100 ^ 101 results in 001
101 ^ 100 results in 001
AND NOT
111 &^ 101 results in 010
101 &^ 111 results in 000

And finally, &^= is a shorthand assignment operator. For example, x = x &^ y can be replaced by x &^= y

Upvotes: 11

Mitch
Mitch

Reputation: 22251

The spec says that they are the bit clear operators:

&^   bit clear (AND NOT)    integers

You would use them as part of a bit flag value. You'd use or to turn on a bit, and and not to turn it off.

Upvotes: 1

Related Questions