Golang XOR: A Bitwise Operator

The XOR operator in Golang “compares the corresponding bits of two numbers and returns a new number where each bit is set to 1 if and only if exactly one of the corresponding bits in the operands is 1”. The “^” symbol represents the bitwise XOR (exclusive OR) operator.

The bitwise operators take both signed and unsigned integers as input. However, a shift operator’s right-hand side must be an unsigned integer.

The ^ operator in Go performs OR operations between two integer numbers provided as an operand.

It has the following characteristics.

Golang XOR operator

In the above table, the output is 1 only when both the input values differ.

If both input values are the same, it will result in 0 when XORed. The XOR operator has many interesting uses in computing.

The XOR is used to toggle values, such as changing values from 0 to 1 and 1 to 0 in a sequence of bits. 

Binary XOR Operator copies the bit if it is set in one operand but not both. So, for example, (A ^ B) will give 49, which is 0011 0001.


package main

import "fmt"

func main() {
  a := 19
  b := 21
  c := a ^ b
  fmt.Printf("The Value of c is %d\n", c)


The Value of c is 6

In the example above, the variable c will contain the value 6 (110 in binary) because only the leftmost and rightmost bits differ between a and b. All other bits are the same, resulting in a 0 bit.

The XOR operator can be used for many purposes, such as flipping individual bits, comparing two numbers to see which bits are different, and generating random numbers.