Sign Extension

Unintended sign extension is a common problem when converting to 64–bits.
It is hard to detect before the problem actually occurs because lint(1) does
not warn you about it. Furthermore, the type conversion and promotion rules are somewhat
obscure. To fix unintended sign extension problems, you must use explicit casting
to achieve the intended results.

To understand why sign extension occurs, it helps to understand the conversion
rules for ANSI C. The conversion rules that seem to cause the most sign extension
problems between 32-bit and 64-bit integral values are:

Integral promotion

A char, short, enumerated type, or bit-field, whether signed or unsigned,
can be used in any expression that calls for an int. If an int can hold all possible values of the original type, the value is converted
to an int. Otherwise, it is converted to an unsigned int.

Conversion between signed and unsigned integers

When
a negative signed integer is promoted to an unsigned integer of the same or larger
type, it is first promoted to the signed equivalent of the larger type, then converted
to the unsigned value.

For a more detailed discussion of the conversion rules, refer to the ANSI C
standard. Also included in this standard are useful rules for ordinary arithmetic
conversions and integer constants.

When compiled as a 64-bit program, the addr variable in the following
example becomes sign-extended, even though both addr and a.base are unsigned types.

This sign extension occurs because the conversion rules are applied as follows:

a.base is converted from an unsigned int to an int because of the integral promotion rule. Thus, the expression a.base << 13 is of type int, but no sign extension has
yet occurred.

The expression a.base << 13 is of type int, but it is converted to a long and then to an unsigned
long before being assigned to addr, because of the signed
and unsigned integer promotion rule. The sign extension occurs when it is converted
from an int to a long.