Bitwise Operators

Bitwise Operators in Go #

Bitwise operators are used to perform operations on binary numbers.

List of Bitwise Operators #

OperatorNameDescriptionExample
&ANDSets each bit to 1 if both bits are 1x & y
``ORSets each bit to 1 if one of two bits is 1
^XORSets each bit to 1 if only one of two bits is 1x ^ y
<<Zero fill left shiftShift left by pushing zeros in from the rightx << 2
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the leftx >> 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)
}