does in c++ the conversion from unsigned int to int always preserve the bit pattern?

前端 未结 3 1134
我在风中等你
我在风中等你 2021-02-13 15:37

From the standard (4.7) it looks like the conversion from int to unsigned int, when they both use the same number of bits, is purely conceptual:

If the de

3条回答
  •  暖寄归人
    2021-02-13 16:24

    "Destination type" refers to the type you're assigning/casting to.

    The whole paragraph means a 32 bit unsigned int converted to a 32 bit signed int will stay as-is, given the value fits into the signed int. If they don't fit, it depends on the implementation on what it does (e.g. truncate). That means it really depends on the implementation whether the bits stay or whether they're changed (there's no guarantee).

    Or in other words: If the unsigned int uses its most significant bit, the result is no longer predictable. Otherwise there's no change (other than changing the "name on the box").

提交回复
热议问题