C left shift by 64 bits

I have this code in C (it is for study only):

char x; uint64_t total = 0; for(x = 20; x < 30; x++){ total = (((((1 << x) * x) / 64) + 1) * sizeof(uint64_t)); printf("%d - %llu\n", x, total); } 

What is printed:

 20 - 2621448 21 - 5505032 22 - 11534344 23 - 24117256 24 - 50331656 25 - 104857608 26 - 218103816 27 - 18446744073625665544 28 - 18446744073575333896 29 - 18446744073508225032 

Why at x> 26 do I have these strange values? I'm on gcc 4.6.1 on Ubuntu 10.10 64 bit.

+6
source share
2 answers

Because 1 is int , 32 bits, so (1 << 27)*27 overflowed. Use 1ull .

As for your comment, if x is uint64_t , then 1 << x is still int , but for multiplication it will be different to uint64_t , so there will be no overflow. However, if x >= 31 , 1 << x will be undefined behavior (since the resulting value cannot be represented as an integer type of 32-bit character).

+19
source

I think your problem is that you are calculating with a 32-bit version and assigning it later to a 64-bit value

dividing by 64 is the same as not shifting 6 bits

 char x; uint64_t one = 1; uint64_t total = 0; for(x = 20; x < 30; x++){ total = ((((one << (x - 6)) * x) + 1) * sizeof(uint64_t)); printf("%d - %llu\n", x, total); } 

not compiled yet

0
source

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


All Articles