c - integer downcast

后端 未结 3 2091
有刺的猬
有刺的猬 2020-12-31 15:45

About integer numbers downcasts in C, e.g.

An int value 000F\'E000 downcast to short or unsigned short will become E000.
shor

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 15:58

    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.

提交回复
热议问题