Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to get the one's compliment and why it is just making it negative and just adding 1 on it?

+3 votes
asked Oct 20, 2021 by Lexus Guevara (1,060 points)
#include <stdio.h>

int main()

{

int a = 9, b;

b = ~a;

printf("The answer is %d.");

return 0;

}

OUTPUT:

The answer is -10.

2 Answers

0 votes
answered Oct 20, 2021 by Peter Minarik (101,360 points)

Please, read ones' complement, and two's complement as well.

TL; DR; To get ones' complement you invert all the bits. This includes the sign bit (since your type is a signed int). That's why it will be negative. Also, negative numbers are represented as two's complement. But since two's complement = ones' complement + 1, your result will be one less than the original number with its sign flipped. (ones' complement = two's complement -1).

Check out this question as well.

0 votes
answered Oct 21, 2021 by PESARLANKA DEVENDRABABU (150 points)

when ever we use bit wise negation (~) one's complement . we can get out put by this formula = -(n+1) 

compiler will convert decimal form (9)  to binary form then we get ( 1001 ) and it will use two's complement (where it will add 1 to (1001) .then it becomes  1010 which is 10 in decimal form the out put will be in the form of negative

 

we get 10 in negative =-10

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...