interpret signed as unsigned

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

    Note that you don't need the cast at all. For all the wrangling about whether the cast will munge bits or not for negative representations, one thing has gotten lost - the cast is completely unnecessary.

    Because of the conversions that C/C++ will do (and how casting is defined), this:

    int64_t s_val = SOME_SIGNED_VALUE;
    uint64_t u_val = s_val;
    

    is exactly equivalent to:

    int64_t s_val = SOME_SIGNED_VALUE;
    uint64_t u_val = static_cast(s_val);
    

    That said, you might still want the cast because it signals intent. However, I've heard it argued that you shouldn't use unnecessary casts because it can silence the compiler in situations where you might want a warning.

    Pick your poison.

提交回复
热议问题