Home > Blockchain >  Why does ^1 equal -2?
Why does ^1 equal -2?

Time:04-12

fmt.Println(^1)

Why does this print -2?

CodePudding user response:

The ^ operator is the bitwise complement operator. Spec: Arithmetic 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 1 in binary is a single 1 bit preceded with full of zeros:

0000000000000000000000000000000000000000000000000000000000000001

So the bitwise complement is a single 0 bit preceded by full of ones:

1111111111111111111111111111111111111111111111111111111111111110

The ^1 is an untyped constant expression. When it is passed to a function, it has to be converted to a type. Since 1 is an untyped integer constant, its default type int will be used. int in Go is represented using the 2's complement where negative numbers start with a 1. The number being full ones is -1, the number being smaller by one (in binary) is -2 etc.

The bit pattern above is the 2's complement representation of -2.

To print the bit patterns and type, use this code:

fmt.Println(^1)
fmt.Printf("%T\n", ^1)
fmt.Printf("4b\n", 1)
i := ^1
fmt.Printf("4b\n", uint(i))

It outputs (try it on the Go Playground):

-2
int
0000000000000000000000000000000000000000000000000000000000000001
1111111111111111111111111111111111111111111111111111111111111110

CodePudding user response:

Okay, this has to do with the way that we use signed signs in computation.

For a 1 byte number, you can get

D B
-8 1000
-7 1001
-6 1010
-5 1011
-4 1100
-3 1101
-2 1110
-1 1111
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111

You can see here that 1 is equivalent to 0001 (Nothing changes) but -1 is equal to 1111. ^ operator does a bitwise xor operation. Therefore:

0001
1111 xor
-------
1110 -> That is actually -2. 

All this is because of the convention of two complement that we use to do calculations with negative numbers. Of course, this can be extrapolated to longer binary numbers.

You can test this by using windows calculator to do a xor bitwise calculation.

  • Related