29

I hope this question is not too stupid... I have no idea what the ^ operator does in Go, e.g.

a := 3^500

At first I thought it must be pow but it most certainly is not. It's not mod (%) either.

I've tried looking through the doc and searching on Google, but unfortunately Google doesn't think ^ is a search term.

Rambatino
  • 4,716
  • 1
  • 33
  • 56
Alasdair
  • 13,348
  • 18
  • 82
  • 138

1 Answers1

36

As in most languages, the caret operator is a bitwise XOR. You use it on integers.

Relevant Golang documentation

Wikipedia on the bitwise xor :

A bitwise XOR takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. In this we perform the comparison of two bits, being 1 if the two bits are different, and 0 if they are the same

The bitwise XOR may be used to invert selected bits in a register (also called toggle or flip). Any bit may be toggled by XORing it with 1. For example, given the bit pattern 0010 (decimal 2) the second and fourth bits may be toggled by a bitwise XOR with a bit pattern containing 1 in the second and fourth positions:

     0010 (decimal 2)
 XOR 1010 (decimal 10)
   = 1000 (decimal 8)

This technique may be used to manipulate bit patterns representing sets of Boolean states.

Adding the comment from @karmakaze to this answer for more helpful info:

Also as a unary operator, it's bitwise not. e.g. ^uint(0) results in the uint value 0xffffffff for 32-bit machine and longer for a 64-bit machine.

Pallav Jha
  • 3,409
  • 3
  • 29
  • 52
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 11
    Also as a unary operator it's bitwise not. e.g. `^uint(0)` results in the uint value `0xffffffff` for 32-bit machine and longer for 64-bit machine. – karmakaze Feb 24 '16 at 02:13
  • @karmakaze you should edit/improve the answer by appending your comment. – Pallav Jha May 06 '20 at 15:42