Reputation: 53
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
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)
&
): Result is 1 when both operand bits are 1, else the result is 0.|
): Result is 1 when at least one operand bit is 1, else 0 if both operand bits are 0.^
): 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.&^
): 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