How does one safely static_cast between unsigned int and int?

后端 未结 6 1282
猫巷女王i
猫巷女王i 2021-02-19 19:36

I have an 8-character string representing a hexadecimal number and I need to convert it to an int. This conversion has to preserve the bit pattern for

6条回答
  •  情深已故
    2021-02-19 19:56

    Here's another solution that worked for me:

    if (val <= INT_MAX) {
        return static_cast(val);
    }
    else {
        int ret = static_cast(val & ~INT_MIN);
        return ret | INT_MIN;
    }
    

    If I mask off the high bit, I avoid overflow when casting. I can then OR it back safely.

提交回复
热议问题