0
void main()
{
        unsigned int a = 10;
        a = ~a;
        printf("%d\n", a);
}

the output is -11

10 = 1010

~10 = 0101

why the output is negative?

6
  • Use printf("%u\n", a); and try again. Commented Mar 7, 2014 at 9:18
  • @timrau the output now is 4294967285 Commented Mar 7, 2014 at 9:21
  • Try "%x", it'll be more obvious than in decimal. Commented Mar 7, 2014 at 9:22
  • en.wikipedia.org/wiki/Two%27s_complement Commented Mar 7, 2014 at 9:27
  • int's size must >= 16 bit, char >= 8 bit. There's no 4-bit data type in C Commented Mar 7, 2014 at 9:31

4 Answers 4

2

Use %x to view the consistent hex result.

#include <stdio.h>
void main()
{
        unsigned int a = 10;
        printf("%x\n", a);

        a = ~a;
        printf("%x\n", a);
        return 0;
}

Output:

a
fffffff5
Sign up to request clarification or add additional context in comments.

Comments

1

The result of ~1010 is not 0101 but 11111111111111111111111111110101. All 32 bits of the value are reversed, not only the bits up to the highest set bit.

As the 32nd bit is set in the result, it's negative.

Comments

1

%d is for signed decimal integer. Use %u to print an unsigned integer in decimal.

Comments

0

use %u instead of %d because printf treats your variable according to %d or %u. u for

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.