我有一个unsigned int实际存储有符号值的C++ .我想将此变量转换为a signed int,以便无符号和有符号值具有相同的二进制值.
unsigned int lUnsigned = 0x80000001;
int lSigned1 = (int)lUnsigned; // Does lSigned == 0x80000001?
int lSigned2 = static_cast<int>(lUnsigned); // Does lSigned == 0x80000001?
int lSigned3 = reinterpret_cast<int>(lUnsigned); // Compiler didn't like this
Run Code Online (Sandbox Code Playgroud)
什么时候强制转换在C++中改变变量的位?例如,我知道从a int到a的转换float会改变位,因为它int是二进制补码并且float是浮点数.但其他场景呢?我不清楚C++中的规则.
在C99规范的6.3.1.3节中,它表示从无符号到有符号整数的转换是编译器定义的!