Casting a large number type to a smaller type

Is it guaranteed that if I cast a 16 bit type to an 8 bit type that the leading byte will be lost?

Depends on whether you are working with signed or unsigned types (see section 4.7 §2 and §3):

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation).]

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

Since you are working with unsigned types, the behavior is well-specified.

Leave a Comment