开发者

why -3==~2 in C#

开发者 https://www.devze.com 2023-01-31 07:00 出处:网络
Unable to understand. Why output is \"equal\" code: if (-3 == ~2) Console.WriteLine(\"equal\"); else Console.WriteLine开发者_StackOverflow(\"not equal\");

Unable to understand. Why output is "equal"

code:

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

output:

equal


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.


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


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


Because it uses two's complement.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消