Can you explain me that why the output is -11? | SoloLearn: Learn to code for FREE!

+4

Can you explain me that why the output is -11?

#include<stdio.h> int main() { unsigned int var = 10; printf("%d", ~var); return 0; }

6/2/2020 10:55:12 AM

Shreyam Sarkar

4 Answers

New Answer

+1

It's to do with the way signed integers are represented in binary. The invert, NOT, or complement operator, the tilde character (~) produces the one's complement of a number. That is it flips every bit in the number. All bits that were 1 become 0, and all bits that were 0 become 1. To create a negative number we require the two's complement of that number. The two's complement is created by first obtaining the one's complement then adding one. So a one's complement will always result in a number that is 1 "lower" (more negative) than what you require.. Number 1 0001 binary 1110 one's complement (-2) 1111 two's complement (-1) Number -1 1111 binary 0000 one's complement (0) 0001 two's complement (+1)

+1

Above code gives -11 as output of printf. var is type of unsigned int, var is assigned with 10, operator ~var converts var to complement of 10. printf %d coverts it to integer while printing it's representation makes it -11 in 32 bit binary representation 10 => 0x0000000A -11 => 0xFFFFFFF5 in C language int is represented as 2's complement. That results in to print -11. var contains after complement in 32 bits as 0xFFFFFFF5 2's complement of above is 0x0000000B it is 11 in decimal representation That's why print with format %d prints -11 in output.

+1

Thank you now I understand