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

前端 未结 3 1138
我在风中等你
我在风中等你 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:35

    int is the destination type in this case. As you say 2^32-1 cannot be represented so in this case so it is implementation-specific. Although, I've only ever seen it preserve bit patterns.

    EDIT: I should add that in the embedded world often whats done when one storage location needs multiple representations that are bit-for-bit identical we often use unions.

    so in this case

    union FOO {
        int32_t signedVal;
        uint32_t unsignedVal;
    } var;
    

    var can be accessed as var.signedVal to get the 32 bits stored as a signed int and var.unsignedVal to get the 32 bits stored as an unsigned value. In this case bits will be preserved.

提交回复
热议问题