Reputation: 393
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?
Upvotes: 0
Views: 137
Reputation: 11609
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
Upvotes: 2
Reputation: 1
use %u instead of %d because printf treats your variable according to %d or %u. u for
Upvotes: 0
Reputation: 23058
%d
is for signed decimal integer. Use %u
to print an unsigned integer in decimal.
Upvotes: 1
Reputation: 700152
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.
Upvotes: 1