c - integer downcast

Downcasts

A cast to a smaller integer type discards the most significant (left-most as you'd write the full binary integer on paper) bits that are not present in the destination type.

Upcasts

An upcast to a larger integer is more complex:

  • For unsigned to unsigned types, it adds sufficient zero most-significant bytes; this always preserves the value.
  • For signed to signed types, it sign-extends the the source type (i.e. packs the new byte(s) with bits equal to the sign bit of the source integer); this always preserves the value, positive or negative
  • For unsigned to signed types, it effectively adds sufficient zero-most significant bytes; this always preserves the value, as in the nature of an upcast, there are always more bits in the destination, so there is always space for an extra sign 'bit'
  • For signed to unsigned types, it sign-extends, then casts; this cannot always preserve the value, as a negative value cannot be represented.

Downcast cuts the bits, up-cast depends on "signedness". Up-cast on unsigned types adds zero bits to the value, up-cast on signed types replicates the sign bit. In this way, the expression has the same value before and after an upcast.