interpret signed as unsigned

前端 未结 4 892
不知归路
不知归路 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:11

    I agree static_cast is appropriate in this case, but no one has mentioned a very similar looking case where static_cast wouldn't preserve bits as might be expected.

    char x = -1; // 255
    unsigned int x2 = static_cast(x); // 4294967295
    unsigned int x3 = static_cast(static_cast(x)); // 255
    

    Watch out for sign extension when you are casting from a small signed value to a large unsigned value. Possibly other combinations are vulnerable too - I haven't thought it all the way through.

提交回复
热议问题