The use and meaning of the & ^ and & ^ = operators in Go

Iโ€™ve been looking for about a week and canโ€™t find a decent explanation for these two operators &^ and &^= , in Go language and how they are used. Would anyone be so kind as to enlighten me?

+5
source share
2 answers

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

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

Here, the code is also located on the Go playground , which 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:

 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 

Finally, &^= is the shorthand assignment operator. For example, x = x &^ y can be replaced by x &^= y

+11
source

spec says they are bitwise operators:

 &^ bit clear (AND NOT) integers 

You would use them as part of the value of the bit flag. You must use or to enable the bit, and and not to disable it.

+1
source

Source: https://habr.com/ru/post/1207555/


All Articles