Why doesn't ~ 0 >> 1 shift the bit?

I just found out from the book K & R c Chapter 2, let's say I have this code:

#include <stdio.h>
int
main(void)
{
    printf("0x%016llx\n", ~0); //0x00000000ffffffff

    printf("0x%016llx\n", ~0 >> 1); //0x00000000ffffffff
    printf("0x%016llx\n", 0x00000000ffffffff >> 1); //0x000000007fffffff
    return 0;
}

I expect to ~0 >> 1give 0x000000007fffffffhow it does 0x00000000ffffffff >> 1, which ~0matters 0x00000000ffffffff.

Why ~0 >> 1does not shift the bit?

+4
source share
2 answers

The format llxspecifier expects an argument unsigned long long, but you pass int.

The shift does not give you what you expect, because it ~0results in inta negative value. Thus, the right shift preserves the sign bit, i.e. The bit is 1shifted to the left.

ULL , :

printf("0x%016llx\n", ~0ULL);
printf("0x%016llx\n", ~0ULL >> 1);
printf("0x%016llx\n", 0x00000000ffffffffULL >> 1);

:

0xffffffffffffffff
0x7fffffffffffffff
0x000000007fffffff

, 0 .

+6

...

printf("0x%016llx\n", ~0)

... undefined, (int) ~0 %llx, unsigned long long int.

~0 >> 1 , ( undefined),

E1 >> E2 E1 E2 [, ] E1 , .

(C2011, 6.5.7/5)

, , , :

  • , , ,

  • , , , .

(, ). , .

+2

Source: https://habr.com/ru/post/1663019/


All Articles