Go Bitwise Operators

Introduction

Go bitwise operators are used to do bit level operation on numbers.

The following table lists the Go bitwise operators.

Operator Name Description
&AND Sets bit to 1 if both bits are 1
|OR Sets bit to 1 if one of two bits is 1
^XOR Sets bit to 1 if only one of two bits is 1
<< Zero fill left shift Shift left by pushing zeros in from the right and discard the left most bits
>> Signed right shift Shift right by pushing copies of the left most bit in from the left, and discard the right most bits

The following example shows how to use bitwise operators.

package main //w w  w  .  ja  v  a  2s  . c  o  m

import "fmt"

func main() {
  var x uint = 7  
  var y uint = 65 
  var z uint

  z = x & y
  fmt.Println("x & y  =", z)

  z = x | y
  fmt.Println("x | y  =", z)

  z = x ^ y
  fmt.Println("x ^ y  =", z)

  z = x << 1
  fmt.Println("x << 1 =", z)

  z = x >> 1
  fmt.Println("x >> 1 =", z)
}



PreviousNext

Related