Bitwise Operators in Go #
Bitwise operators are used to perform operations on binary numbers.
List of Bitwise Operators #
Operator | Name | Description | Example |
---|---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 | x & y |
` | ` | OR | Sets each bit to 1 if one of two bits is 1 |
^ | XOR | Sets each bit to 1 if only one of two bits is 1 | x ^ y |
<< | Zero fill left shift | Shift left by pushing zeros in from the right | x << 2 |
>> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left | x >> 2 |
Example #
package main
import ("fmt")
func main() {
var x uint = 5 // 0101 in binary
var y uint = 3 // 0011 in binary
fmt.Println(x & y) // 1 (0001)
fmt.Println(x | y) // 7 (0111)
fmt.Println(x ^ y) // 6 (0110)
fmt.Println(x << 2) // 20 (10100)
fmt.Println(x >> 1) // 2 (0010)
}