HP C A.06.05 Reference Manual

Expressions and Operators
Cast Operator
Chapter 5100
unsigned char k = 37 55
(short) k => 0037 55
(int) k => 00000037 55
CASE C: Casting Integers to a Smaller Type When an int value is cast to a narrower
type (short or char), the excess bits on the left are discarded. The same is true when a short
is cast to a char, or when a long in 64-bit mode is cast to an int. For instance, if an int is cast
to a short, the 16 leftmost bits are truncated. The following table of values illustrates these
conversions.
hex dec
signed long int i = cf34bf1 217271281
(signed short int)i => 4bf1 19441
(signed char)i => f1 -15
(unsigned char)i => f1 241
If, after casting to a signed type, the leftmost bit is 1, then the number is negative. However, if
you cast to an unsigned type and after the shortening the leftmost bit is 1, then that 1 is part
of the value (it is not the sign bit).
CASE D: Casting from Signed to Unsigned, and Vice Versa When the original type
and the converted type are the same size, a representation change is necessary. That is, the
internal representation of the value remains the same, but the sign bit is interpreted
differently by the compiler. For instance:
hex dec hex dec
signed int i = fffffca9 -855 0000f2a1 62113
(unsigned int)i => fffffca9 4294966441 0000f2a1 62113
The hexadecimal notation shows that the numbers are the same internally, but the decimal
notation shows that the compiler interprets them differently.
CASE E: Casting Signed to Unsigned and Widening This case is equivalent to
performing two conversions in succession. First, the value is converted to the signed widened
type as described in case B, and then it is converted to unsigned as described in case D. In the
following assignments, the new leftmost bits are filled with ones to preserve negativeness
even though the final value is unsigned.
hex dec
signed short int i = ff55 -171
(unsigned long int)i => fffff55 4294967125