Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

.net - why -3==~2 in C#

Unable to understand. Why output is "equal"

code:

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

output:

equal
question from:https://stackoverflow.com/questions/4471823/why-3-2-in-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...