Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 982
Javed Akram Avatar asked Dec 17 '10 15:12

Javed Akram


People also ask

Why #is used in C?

In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more. It actually adds code to the source file before the final compilation.

What is the result of dividing 3 by 2 in C++?

@Woot4Moo: snarky can be fun, but in this case it's just dumb. Integral division has very specific rules regarding truncation, and the fact is that 3/2 == 1 . – Matthieu M.

What does || stands for in C?

Logical Operators If both the operands are non-zero, then the condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.

What is the answer of 7 3 in C programming?

(nk)=n! (n−k)!k! Which means that: (73)=7!


1 Answers

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.

like image 114
Daniel DiPaolo Avatar answered Oct 14 '22 01:10

Daniel DiPaolo