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
string
int
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.