1

I found some wired problems when I tried to do left shift for 32 times. The code in the test function should print the same results of 0x0, but I got "ffffffff, 0" instead. Anybody could give a hint of what's wrong with the code? Thank you!

int test(int n) { int mask = ~0 << (32 + ~n + 1); int mask1 = ~0 << (32 + ~0 + 1); printf("%x, %x\n", mask, mask1); return mask; } int main(){ test(0); } 
2
  • same with stackoverflow.com/questions/3784996/… Commented May 7, 2013 at 16:30
  • Can you try making the int declaration an unsigned int and tell us if it will make any difference? Commented Jan 7, 2014 at 19:54

2 Answers 2

4

In C, shifting with size greater than the type size (int in your case) is an undefined behavior

From this topic: Relevant quote from ISO C99 (6.5.7/4)

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

Sign up to request clarification or add additional context in comments.

2 Comments

You mean it is still undefined if the shifting distance is the same a s the type size?
yes. if your type size is 32 then you are allowed to shift with number <= 31
2

Assuming you have 32-bit integers, the results of left shifting more than 31 times are undefined

From C11 §6.5.7 Bitwise shift operators

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 x 2E2 , reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 x 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.