Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

negation of a number

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

like image 519
debonair Avatar asked Dec 16 '22 02:12

debonair


1 Answers

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".

like image 113
Ray Toal Avatar answered Jan 06 '23 05:01

Ray Toal