Ones compliment of unsigned integer | Sololearn: Learn to code for FREE!

+3

Ones compliment of unsigned integer

unsigned int a=10; a=~a; printf("%d\n",a); O/P:- -11 1's compliment of 10 is 1010 -> 0101 Why o/p is -11 ???

11/27/2020 6:28:57 AM

Ajith

6 Answers

New Answer

+4

This question is really interesting. The ~ operator follows both one's compliment and two's compliment(depending on the situation).In your program,It follows two's compliment .A unsigned int is 2 to 4 byte depending on the compiler. If I think the unsigned int is 2 byte then 2 byte =16 bit. so the value of 10 in binary is 0000 0000 0000 1010 so when you use a=~a, the value becomes in binary is(for 2 byte): 1111 1111 1111 0101 So the value becomes -2^15+(2^14+2^13+2^12+2^11+2^10+2^9+2^8+2^7+2^6+2^5+2^4+2^2+2^0)=-11 If you don't know two's component you can have a look at this video: https://www.youtube.com/watch?v=4qH4unVtJkE but this is not the answer you were expecting because you used unsigned int so it should follow one's complement and the answer should not be negative right? Yes, you are right but the problem is: The "%d" format is for (signed) int values. If you use it with an unsigned value, it could print something other than the actual value(like here it prints negative value and follows the two's complement). Use "%u" to see the actual value.Here is the detailed answer: https://stackoverflow.com/questions/7152759/what-happens-when-i-assign-a-negative-value-to-an-unsigned-int When you will use printf("%u\n",a); , It will follow the one's component like you expected. In sololearn compiler, unsigned int use 4 byte memory means 32 bit memory. So since you assigned a =10, in binary the value will be, 0000 0000 0000 0000 0000 0000 0000 1010 so if you use ~a in binary, value will be : 1111 1111 1111 1111 1111 1111 1111 0101 Now for simple calculation, 1111 1111 1111 1111 1111 1111 1111 1111 (32 bit) =4,294,967,295(unsinged int) -0000 0000 0000 0000 0000 0000 0000 1010=10 =1111 1111 1111 1111 1111 1111 1111 0101 =4,294,967,285 So the answer will be 4,294,967,285. Here is the code: https://code.sololearn.com/cpV68Dgd53ta/#c

+6

You got -11 because you used %d to print an `unsigned int` value. Try with %u, and you'll see that `unsigned int` representation of -11.

+6

Yes i got it.... Thank you Ipang Arsenic Azhagesanヾ(˙❥˙)

+3

Here is the detailed explanation https://www.sololearn.com/learn/4076/?ref=app

+3

Have a look at this 👇 https://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-tilde-work

+3

Yes i tried with %u and i got it why the value is negative. Zatch bell thank you so much for your answer and it cleared some more doubt of mine.👍