Question

hello i wrote a small program to demonstrate the problem that i'm facing

long n;
n = 1;    //1=0001  //2=0010 //-2=1101

Console.WriteLine(n+" "+ ~n);
Console.WriteLine(n+~n);

and the output is something like this :

1 -2
-1

as i know ~ sign should give same negative number, but the number that i'm getting is all the time one more than the original number according to following link the answer that i have to get should be same, and if i add the negation to the original number i should get 0 not another number http://visualcsharptutorials.com/reference/converting-negative-numbers-to-binary

can anyone tell me what is wrong with it? i'm using .net 4.5, c#5.0, vs 2012

Was it helpful?

Solution

The system you're describing is called ones' complement and it's not the system used in most modern environments (including C#). What is used is two's complement. In this system, -1 is 1111, -2 is 1110, etc. That means the numbers you're getting are correct, because ~1 == -2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top