This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Bit shifting of signed variables

Is left and right shifting of signed(negative) variables supported by the compiler . My understanding is that this is not a requirement in ANSI C and can be platform dependant .

 

The Micro I am using is the piccalo I am using the code composer studio v 4.2.4

  • All TI compilers support left and right shift of signed integer types.  Left shifts are handled identically to unsigned left shifts.  Right shifts are arithmetic (sign-preserving) right shifts.

  • I am pretty sure that what is allowed to be platform dependent in ANSI is the sign of the right hand side of the bit shift operator.  In other words, this code may or may not do what you expect:

     

    int shift = -1, x = 2, y;

    y = x << shift;

     

    y may be 1, or it may not.

     

  • I'm sorry, that's not correct.  The standard explicitly says that shift values that are negative, or greater than or equal to the size of the type, are undefined.  C99 section 6.5.7 (ANSI C89 section 3.3.7, sorry I don't have the ISO C89 section number handy) "Bitwise shift operators", paragraph 3.  The TI compiler does not support negative shift counts without an intrinsic.

    For a signed left shift, if the result overflows, it is undefined behavior, just as multiplication would be (paragraph 4).  For signed right shifts of a negative value, the result is implementation-defined (paragraph 5).

  • I don't think what I said was incorrect, just perhaps not as verbose as what you said.  The standard says that the result is undefined, which is the same thing as saying processor dependent. 

    I was trying to state that a negative left shift might be equivalent to a positive right shift on some processors.  On other processors it will be a really big positive left shift.  Since the result is not defined such code should be avoided.

     

  • "undefined behavior" means the compiler is free to do anything at any time.  It's not guaranteed to work the same way twice.  The compiler could do what you expect on Tuesdays and erase your hard drive on Wednesdays, and it would still be a conforming implementation. 

    "implementation-defined" means the compiler must pick a behavior and stick to it.

    Of course, any compiler is free to add definition to whatever area of undefined behavior it pleases, so some compiler could indeed do what you've described.  The TI compiler does not define shifts by negative counts.