Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it possible to right shift a signed variable? (12.7)
#2
Rule 12.7 prohibits shifting of signed types because the result depends on how your compiler chooses to represent types and how it performs shifts. The specific problem with right shifting a signed value is that the compiler is free to choose whether the sign bit is filled with 0 or filled with copies of the sign bit. So (in binary) 10... >> 1u could either be 01... or 11... (where the ... represent least significant bits).

As is the case with several MISRA C rules, the purpose behind this rule is to make programmers think about what they want to achieve and then code it appropriately.

If you want to guarantee that 0 is shifted into the vacated bits then you could cast the signed variable to an unsigned version, perform the shift, and then cast the result back. This works because conversion of signed to unsigned of the same size won't change the bit pattern (on a 2s complement machine at least) and the result will be guaranteed to fit in the signed type as it will be no larger than the original value.

If you want to copy the sign bit into the vacated bits then check the documentation for your compiler. It should tell you somewhere whether right shifts on signed quantities preserve the sign bit or not. If they do, then I would recumbent raising a deviation against this rule on the grounds that your implementation guarantees to do exactly what you want. If you aren't able to raise a deviation, or your implementation doesn't preserve the sign bit, then I think you'll need to write a function to achieve what you want, possibly or even probably in assembly language.
<t></t>
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 2 Guest(s)