interpret signed as unsigned

前端 未结 1 598
伪装坚强ぢ
伪装坚强ぢ 2021-02-11 19:30

I have a value like this:

int64_t s_val = SOME_SIGNED_VALUE;

How can I get a

uint64_t u_val

that has exactly

相关标签:
1条回答
  • 2021-02-11 20:34
    int64_t s_val = SOME_SIGNED_VALUE;
    uint64_t u_val = static_cast<uint64_t>(s_val);
    

    C++ Standard 4.7/2 states that:

    If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n 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). ]

    From the other hand, Standard says that "The mapping performed by reinterpret_cast is implementation-defined. [Note: it might, or might not, produce a representation different from the original value. ]" (5.2.10/3). So, I'd recommend to use static_cast.

    0 讨论(0)
提交回复
热议问题