简体   繁体   中英

printf tilde operator in c

I know that the ~ operator is NOT, so it inverts the bits in a binary number

unsigned int a = ~0, b = ~7;
printf("%d\n",a);
printf("%d\n",b);
printf("%u\n",a);
printf("%u\n",b);

I guessed 0 will be 1 and 7 (0111) will be 8 (1000) but the output was

-1
-8
4294967295
4294967288

how did ~0 and ~7 become -1, and -8? also why is %u printing that long number?

The ~ operator simply inverts all bits in a number.

On most modern compilers, int is 32 bits in size, and a signed int uses 2's complement representation. Which means, among other things, that the high bit is reserved for the sign , and if that bit is 1 then the number is negative.

0 and 7 are int literals. Assuming the above, we get these results:

  • 0 is bits 00000000000000000000000000000000b
    = 0 when interpreted as either signed int or unsigned int

  • ~0 is bits 11111111111111111111111111111111b
    = -1 when interpreted as signed int
    = 4294967285 when interpreted as unsigned int

  • 7 is bits 00000000000000000000000000000111b
    = 7 when interpreted as either signed int or unsigned int

  • ~7 is bits 11111111111111111111111111111000b
    = -8 when interpreted as signed int
    = 4294967288 when interpreted as unsigned int

In your printf() statements, %d interprets its input as a signed int , and %u interprets as an unsigned int . This is why you are seeing the results you get.

The ~ operator inverts all bits of the integer operand. So for example where int is 32-bit, 1 is 0x00000001 in hex and it's one's complement is 0xFFFFFFFE. When interpreted as unsigned, that is 4 294 967 294, and as two's complement signed, -2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM