问题
Unable to understand. Why output is "equal"
code:
if (-3 == ~2)
Console.WriteLine("equal");
else
Console.WriteLine("not equal");
output:
equal
回答1:
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.
回答2:
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
回答3:
It's due to the two's complement representation of signed integers: http://en.wikipedia.org/wiki/Twos_complement
回答4:
Because it uses two's complement.
回答5:
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
回答6:
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.
来源:https://stackoverflow.com/questions/4471823/why-3-2-in-c-sharp