gpt4 book ai didi

c++ - 有符号整数和无符号整数之间的转换

转载 作者:搜寻专家 更新时间:2023-10-31 00:10:38 31 4
gpt4 key购买 nike

如果我将一个无符号整数转换为一个有符号整数然后再转换回去,我能保证得到原始值吗?例如,根据 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));
}

最佳答案

fg 的答案都是“不,这不能保证”。

标准是这样说的:

4.7 Integral conversions

  1. 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 ]
  2. 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 可能会导致在不使用二进制补码表示的系统上的表示发生变化,因此将数字转换回来可能会得到不同的值。

第 3 节讨论函数 f。当数字超出 signed int 的范围时,结果是实现定义的,因此不允许对将其转换回 unsigned 的结果做出任何声明。

关于c++ - 有符号整数和无符号整数之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37450336/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com