interpret signed as unsigned

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

    Generally speaking, it doesn't matter whether you use static_cast or reinterpret_cast. So long as you are running on a processor that uses two's complement to represent negative numbers, the result is the same. (Practically all modern processors use that.) Under two's complement, a positive number in a signed int is represented the same way in an unsigned int; if it's a negative number it'll be reinterpreted as a large positive number in the unsigned form.

    Basically, what your cast does is tell the compiler to produce different assembly instructions when dealing with that value. E.g. there are different instructions for multiplication and division for signed integers. Although addition and subtraction remains the same (read the wikipedia link and you'll understand).

提交回复
热议问题