38

Unable to understand. Why output is "equal"

code:

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

output:

equal
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Javed Akram
  • 15,024
  • 26
  • 81
  • 118
  • 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
  • 55,313
  • 14
  • 116
  • 115
  • 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,946
  • 17
  • 95
  • 158
3

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

Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
2

Because it uses two's complement.

Simone
  • 11,655
  • 1
  • 30
  • 43
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,572
  • 4
  • 41
  • 50
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
  • 761
  • 4
  • 9