Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C left shift on 64 bits fail

I have this code in C (it's 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 those strange values? I'm at gcc 4.6.1 on Ubuntu 10.10 64 bits.

like image 485
Frederico Schardong Avatar asked Apr 06 '12 19:04

Frederico Schardong


People also ask

What does << In C mean?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

How does Left Shift work in C?

Left Shift and Right Shift Operators in C/C++ Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. Or in other words left shifting an integer “x” with an integer “y” denoted as '(x<<y)' is equivalent to multiplying x with 2^y (2 raised to power y).

How does a left shift work in bitwise?

Bitwise Shift Operators Left Shift(<<): The left shift operator, shifts all of the bits in value to the left a specified number of times. Syntax: value << num. Here num specifies the number of position to left-shift the value in value.

Which is used to shift all of the bits in a value to the left side of a specified number of times?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.


1 Answers

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

Regarding your comment, if x is a uint64_t, then 1 << x is still an int, but for the multiplication it would be cast to uint64_t, so there'd be no overflow. However, if x >= 31, 1 << x would be undefined behaviour (as the resulting value cannot be represented by a signed 32 bit integer type).

like image 158
Daniel Fischer Avatar answered Sep 27 '22 21:09

Daniel Fischer