# Unary integer operators

### February 2, 2024

We have a quick one today to finish up integer operators, before diving into a semi-hairy topic next…

#### Integer operators

For integer operands, the unary operators `+`, `-`, and `^` are defined as follows:

``````+x                          is 0 + x
-x    negation              is 0 - x
^x    bitwise complement    is m ^ x  with m = "all bits set to 1" for unsigned x
and  m = -1 for signed x
``````

So the first two are pretty obvious… `+` and `-` just allow you to specify the sign of a thing. `+` is rarely used, because it does, well… nothing. LOL.

`+x` is always equal to `x`.

`-` on the other hand, is how you specify a literal negative number. Actually, you can’t express a literal negative number in Go… you can only apply the `-` operator to a positive number!

But that third one… `^`… that’s a little more archaic, and requires some explanation. It’s a bitwise operation, so I’ll demonstrate using binary representations of data:

``````x := uint(0b101010)    // decimal 42 in binary
fmt.Printf("%b\n", ^x) // 1111111111111111111111111111111111111111111111111111111111010101
``````

As you can see, this just flips the bits:

``````0000000000000000000000000000000000000000000000000000000000101010
1111111111111111111111111111111111111111111111111111111111010101
``````

I chose `uint` to demonstrate with an unsinged integer, because the binary is easier to reason about, but it does the same with signed ints (i.e. `int`), but two’s compliment math makes it a bit tricker to reason about. Let’s leave it at: it does the same thing at the bit level.

Quotes from The Go Programming Language Specification Version of August 2, 2023