DEV Community

Kevin Albertson
Kevin Albertson

Posted on

Bit shift wraps values

#c
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>

int main () {
    for (uint32_t shift = 0; shift < 35; shift++) {
        uint32_t u32 = UINT32_MAX >> shift;
        printf ("1 >> %02" PRIu32 " = %" PRIu32 "\n", shift, u32);
    }
}
Enter fullscreen mode Exit fullscreen mode

This example may be run here.

I expected that UINT32_MAX >> 32 to result in 0. But the output disagrees:

1 >> 00 = 4294967295
1 >> 01 = 2147483647
1 >> 02 = 1073741823
1 >> 03 = 536870911
1 >> 04 = 268435455
1 >> 05 = 134217727
1 >> 06 = 67108863
1 >> 07 = 33554431
1 >> 08 = 16777215
1 >> 09 = 8388607
1 >> 10 = 4194303
1 >> 11 = 2097151
1 >> 12 = 1048575
1 >> 13 = 524287
1 >> 14 = 262143
1 >> 15 = 131071
1 >> 16 = 65535
1 >> 17 = 32767
1 >> 18 = 16383
1 >> 19 = 8191
1 >> 20 = 4095
1 >> 21 = 2047
1 >> 22 = 1023
1 >> 23 = 511
1 >> 24 = 255
1 >> 25 = 127
1 >> 26 = 63
1 >> 27 = 31
1 >> 28 = 15
1 >> 29 = 7
1 >> 30 = 3
1 >> 31 = 1
1 >> 32 = 4294967295
1 >> 33 = 2147483647
1 >> 34 = 1073741823
Enter fullscreen mode Exit fullscreen mode

1 >> 32 is undefined behavior by the C standard 6.5.7 of left shift:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

TIL

Top comments (0)