38

Unable to understand. Why output is "equal"

code:

 if (-3 == ~2)           
    Console.WriteLine("equal");
 else
    Console.WriteLine("not equal");

output:

equal
Josh Lee
  • 161,055
  • 37
  • 262
  • 269
Javed Akram
  • 14,674
  • 24
  • 78
  • 117
  • possible duplicate of [Why is ~3 equal to -4 in Python?](http://stackoverflow.com/questions/3916753/why-is-3-equal-to-4-in-python) – Josh Lee Dec 18 '10 at 00:13
  • possible duplicate of [How does the bitwise complement (~) operator work?](http://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-work) – phuclv Sep 14 '14 at 17:23

6 Answers6

61

Because two's complement bit-arithmetic makes it so

Cribbed from the wikipedia page and expanded:

Most
Significant
Bit          6  5  4  3  2  1  0   Value
0            0  0  0  0  0  1  1   3
0            0  0  0  0  0  1  0   2
0            0  0  0  0  0  0  1   1 
0            0  0  0  0  0  0  0   0
1            1  1  1  1  1  1  1   -1
1            1  1  1  1  1  1  0   -2
1            1  1  1  1  1  0  1   -3
1            1  1  1  1  1  0  0   -4

So you get:

0  0  0  0  0  0  1  0  =  2
1  1  1  1  1  1  0  1  = -3

And as you can see, all the bits are flipped, which is what the bitwise NOT operator (~) does.

Daniel DiPaolo
  • 53,439
  • 13
  • 112
  • 113
  • 7
    And for those curious about why negative numbers are represented this way, try adding -1 to 1 and see how you arrive at zero :-) – phkahler Dec 17 '10 at 16:20
8

This stackoverflow post explains why:

What is the tilde (~) in the enum definition?

is the unary one's complement operator -- it flips the bits of its operand. in two's complement arithmetic, ~x == -x-1

Community
  • 1
  • 1
James Wiseman
  • 29,282
  • 17
  • 92
  • 156
3

It's due to the two's complement representation of signed integers: http://en.wikipedia.org/wiki/Twos_complement

Jackson Pope
  • 14,225
  • 6
  • 53
  • 80
2

Because it uses two's complement.

Simone
  • 11,230
  • 1
  • 28
  • 41
0

There is a big difference between these two operators.

"The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. Bitwise complement operators are predefined for int, uint, long, and ulong."

msdn

Lukasz
  • 7,336
  • 4
  • 38
  • 48
0

The two's complement of 3 is:

1...1101

The (signed) one's complement of 2 is:

1...1101

It's easy to do:

One's complement: Flip the bits. Two's complement: One's complement + 1.

Why is this useful? Computers can subtract numbers by simply bit flipping and adding.

Nick
  • 751
  • 4
  • 9