Possible Duplicate:
GCC left shift overflow
Consider the following minimal program.
#include <stdint.h>
#include <stdio.h>
int main()
{
uint32_t v = 1024;
v &= (((uint32_t)1 << 32) - 1);
printf("v = %u\n", v);
return 0;
}
This prints 1024 as I would expected compiling with GCC under MinGW. Because 1 shifted 32 times to the left is 0 again, thus 0-1 = -1 which is “1111….1111”. This AND’ed with any value should return the same value again.
However, if I change the program to
#include <stdint.h>
#include <stdio.h>
int main()
{
unsigned int s = 32;
uint32_t v = 1024;
v &= (((uint32_t)1 << s) - 1);
printf("v = %u\n", v);
return 0;
}
The result printed is now 0. Can someone explain this behaviour?
Shifting a 32-bit value by 32 bits is undefined behaviour in C. Don’t do it.