1

when i pass n = 0x0, i get 0xffffffff on the screen which i expect should be 0x00000000 as i shift the word by 32 bits (Just Ignore the x! I didn't use it inside the function.)

void logicalShift(int x, int n) {
    int y = 32;
    int mask = 0xffffffff;
    printf("mask %x", mask << (y-n));
}

One of the interesting point is

void logicalShift(int x, int n) {
    int y = 32;
    int mask = 0xffffffff;
    printf("mask %x", mask << 32);
}

this will output what i expected. Do i miss out anything? Thank you!

Im running on ubuntu

Mandar Pande
  • 12,250
  • 16
  • 45
  • 72
Timothy Leung
  • 1,407
  • 7
  • 22
  • 39

2 Answers2

4

A shift left of 32 bits on a 32 bit value has undefined results. You can only shift 0 to 31 bits.

See also here: Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?

Community
  • 1
  • 1
Tom Tanner
  • 9,244
  • 3
  • 33
  • 61
2

Here is the relevant quote from the C11 draft §6.5.7.3;

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.

In other words, the result is undefined, and the compiler is free to generate any result.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294