Reputation: 2593
int x=8;
int k=~(x);
printf(%d",k)
output: 9
The explanation for it is:
8= 00000000 00000000 00000000 00001000
~8 = 11111111 11111111 11111111 11110111
we are assigning it in integer hence most significant bit (MSB)is the sign bit
bcz MSB is 1 hence it is treated as -ve no.
when u try to print it then before printing compiler will take 2's complement hence it becomes :
2's complement of (~8)=9
2's complement of 11111111 11111111 11111111 11110111
is 00000000 00000000 00000000 00001000 +1 = 1001 = 9
So my question is what if we do k=-9
then if we print k, it will print -9. when does exactly it takes 2's complement
Upvotes: 5
Views: 38869
Reputation: 1420
~8 is -9 check here numbers are represented in 2's compliment. Invert the number and add 1 you will get the positive value of the same number. what you have said is correct for number representation
2's complement of -9 is 11111111 11111111 11111111 11110111 is
00000000 00000000 00000000 00001000 +1
00000000 00000000 00000000 00001001
which 9
Upvotes: 0
Reputation: 88378
The direct but highly technical answer to your question is that the two's complement is taken for an integer value when it is operated on by the negation operator.
More informally: The two's complement of an integer is exactly the same thing as its negation.
If you write
-9
you get the two's complement of 9
which is -9
. If you write
-(-9)
you get the two's complement of -9
which is 9
.
Since you mentioned the the tilde operator (~
) in your question, let's look at that. The tilde operator is the one's complement, which is what you get when you "flip every bit". Notice:
~(-3) = 2
~(-2) = 1
~(-1) = 0
~0 = -1
~1 = -2
~2 = -3
In general
~x = -x - 1
They're different. Use -
for two's complement and ~
for one's complement.
Many people like to rewrite this as
-x = ~x + 1
which gives a hint about how to design a circuit for negation. It means "to find the negation of a number (i.e., its two's complement) you flip every bit then add 1".
Upvotes: 13
Reputation: 4002
when u try to print it then before printing compiler will take 2's complement hence it becomes
This is not true.It is reverse actually. Negative numbers are stored as 2's compliment not converted before printing.
-9
is stored as FFFFFFFFFFFFFFF7
and converted back to -9 when you print it.
Upvotes: 0
Reputation: 3154
The standard for negating a 2's compliment number is to flip all the bits, then add one.
Upvotes: 0