1

This code is not behaving as expected. It simply tries to set bit 31 in an unsigned long int.

int main() {
    printf("sizeof(unsigned long int) is %ld bytes\n", sizeof(unsigned long int));
    unsigned long int v = 1 << 30;
    printf("v is (%lx)\n", v);
    v = 1 << 31;
    printf("v is (%lx)\n", v);
}

Here is the output:

sizeof(unsigned long int) is 8 bytes
v is (40000000)
v is (ffffffff80000000)

Can anyone explain this? Maybe a problem with the printf formatting?

JB_User
  • 3,117
  • 7
  • 31
  • 51

1 Answers1

3

In v = 1 << 31;, 1 is not an unsigned long int. It is an int. Shifting it by 31 bits overflows the int type (in your C implementation).

To get an unsigned long int with a 1 in bit 31, you should shift an unsigned long int by 31 bits: v = (unsigned long int) 1 << 31; or v = 1ul << 31.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312