有符号整数和无符号整数之间的转换
Conversion between signed integer and unsigned integer
如果我将一个无符号整数转换为一个有符号整数然后再转换回去,我能保证得到原始值吗?例如,根据 C++ 标准,此函数是否总是 return true
对于任何平台上的任何 x
?
bool f(unsigned int x)
{
return x == static_cast<unsigned int>(static_cast<int>(x));
}
这个怎么样?
bool g(int x)
{
return x == static_cast<int>(static_cast<unsigned int>(x));
}
f
和 g
的答案都是 "no, this is not guaranteed"。
标准是这样说的:
4.7 Integral conversions
- If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source
integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s
complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]
- If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.
第2节讲函数g
。 x
到 unsigned
的转换可能会导致在不使用二进制补码表示的系统上的表示发生变化,因此将数字转换回来可能会得到不同的值。
第三节讲函数f
。当数字超出 signed int
的范围时,结果是实现定义的,因此不允许对将其转换回无符号的结果做出任何声明。
如果我将一个无符号整数转换为一个有符号整数然后再转换回去,我能保证得到原始值吗?例如,根据 C++ 标准,此函数是否总是 return true
对于任何平台上的任何 x
?
bool f(unsigned int x)
{
return x == static_cast<unsigned int>(static_cast<int>(x));
}
这个怎么样?
bool g(int x)
{
return x == static_cast<int>(static_cast<unsigned int>(x));
}
f
和 g
的答案都是 "no, this is not guaranteed"。
标准是这样说的:
4.7 Integral conversions
- If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]
- If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.
第2节讲函数g
。 x
到 unsigned
的转换可能会导致在不使用二进制补码表示的系统上的表示发生变化,因此将数字转换回来可能会得到不同的值。
第三节讲函数f
。当数字超出 signed int
的范围时,结果是实现定义的,因此不允许对将其转换回无符号的结果做出任何声明。