Using Unsigned Data Types for Portability

[Back]

It is commonly said that for portability, you should perform bitwise shifts only on unsigned characters. You will remember that the most significant bit in a signed character is the sign bit.
When you shift values to the left, C zero-fills the lower bit positions. When you shift values to the right, the value that C places in the most-significant bit position depends on the variables type. If the variable is an unsigned type, C zero-fills the most significant bit. If the variable is a signed type, C fills the most significant bit with a 1 if the value is currently negative, or 0 if the value is positive. This may vary between machines, though. I've seen one case where the expression

a << -5

actually does a left shift of 27 bits- not exactly intuitive.
This is why it is said that you should only use the unsigned data types with bitwise shifts; while it is easy to test how your compiler will handle these shifts, using unsigned data types ensures portability.

[Back]