How does one safely static_cast between unsigned int and int?

后端 未结 6 1259
猫巷女王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:49

    While there are ways to do this using casts and conversions, most rely on undefined behavior that happen to have well-defined behaviors on some machines / with some compilers. Instead of relying on undefined behavior, copy the data:

    int signed_val;
    std::memcpy (signed_val, val, sizeof(int));
    return signed_val;
    

提交回复
热议问题