有符号整数和无符号整数之间的转换 [英] Conversion between signed integer and unsigned integer
问题描述
如果我把一个无符号整数转换为有符号整数,然后回传,我保证得到原始值?例如,对于根据C ++标准在任何平台上的任何 x
,此函数是否始终返回 true
?
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
。
这是标准说的:
4.7积分转换
- 如果目标类型是无符号,则结果值是与源
整数一致的最小无符号整数(模2 n 是用于表示无符号类型的位数。 [注意:在二元的
补码表示中,这种转换是概念性的,并且位模式没有变化(如果没有截断)。 - end note]
- 如果目标类型是signed,则该值不会改变,如果它可以在目标类型中表示;
第2节讲述函数 g
。 x
到 unsigned
的转换可能导致不使用二的补码表示的系统上的表示更改,因此将
第3节介绍函数 f
。当数字在 signed int
的范围之外时,结果是实现定义的,因此不允许有人对将其转换回unsigned的结果提出任何声明。
If I cast an unsigned integer to a signed integer then cast back, am I guaranteed to get the original value? For example, does this function always return true
for any x
on any platform according to the C++ standard?
bool f(unsigned int x)
{
return x == static_cast<unsigned int>(static_cast<int>(x));
}
What about this one?
bool g(int x)
{
return x == static_cast<int>(static_cast<unsigned int>(x));
}
The answer is "no, this is not guaranteed" for both f
and g
.
Here is what the standard says about it:
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.
Section 2 talks about function g
. The cast of x
to unsigned
can cause change of representation on systems that do not use two's complement representation, so converting the number back may get you a different value.
Section 3 talks about function f
. When the number is outside signed int
's range, the result is implementation-defined, so one is not allowed to make any claims about the result of converting it back to unsigned.
这篇关于有符号整数和无符号整数之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!