Size_t 0x1 << 31 is much larger size_t 0x1 << 30

I am confused by some behavior size_tthat I noticed:

size_t zero = 0x1 << 32;
size_t big = 0x1 << 31;
size_t not_as_big = 0x1 << 30;
printf("0x1<<32: %zx\n0x1<<31: %zx\n0x1<<30: %zx\n", zero, big, not_as_big);

Results in:

0x1<<32: 0
0x1<<31: ffffffff80000000
0x1<<30: 40000000

Now I understand that size_tat least a 16-bit unsigned integer is guaranteed, but I don’t understand why it 0x1<<31ends up - trying to allocate 18 exabytes made the number into my program.

I am using LLVM on x86_64.

+3
source share
2 answers

Shifting the signed integer, so that 1 falls into the position of the sign bit or even more undefined in C, so the compiler can do the following:

0x1 << 32

32- int (0x1), 32 . , , 0x1_0000_0000 32- int, 0x0000_0000, , size_t, 64-: 0x0000_0000_0000_0000

0x1 << 31

, , , 1 . , 0x8000_0000, - INT_MIN, . , 64 , , . 0xffff_ffff_8000_0000, 32- , 64- .

64- :

((size_t)1) << 32
((size_t)1) << 31
+9

0x1 int, 32- int :

0x1 << 32

0x1 << 31

undefined.

( , zero 0), , KarolS,

(size_t) 1 << 32

(size_t) 1 << 31

, size_t 32-, clang x64.

+5

All Articles