interpret signed as unsigned

前端 未结 4 875
不知归路
不知归路 2021-02-11 19:54

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

4条回答
  •  滥情空心
    2021-02-11 20:12

    int64_t s_val = SOME_SIGNED_VALUE;
    uint64_t u_val = static_cast(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.

提交回复
热议问题