gpt4 book ai didi

c++ - signed/unsigned int 转换发生了什么?

转载 作者:搜寻专家 更新时间:2023-10-30 23:57:51 25 4
gpt4 key购买 nike

只是仔细检查。在一些教程中我发现了这样的代码:

#include <iostream>
using namespace std;

/* This program shows the difference between
* signed and unsigned integers.
*/
int main()
{
short int i; // a signed short integer
short unsigned int j; // an unsigned short integer

j = 50000;

i = j;
cout << i << " " << j;

return 0;
}

输出:-15536​​ 50000

然后它解释了输出:“上面的结果是因为将 50,000 表示为短无符号整数的位模式被短解释为 -15,536。”

我认为这是一个错误的解释——或者这是一个英语问题?我认为输出负值的原因是 50000 不适合 2 字节的有符号整数,我错了吗?

最佳答案

解释中的推理对于特定平台可能是准确的,但我认为它与最终打印的内容无关。更准确的说法是

"The above result is because the bit pattern returned from an implementation-defined conversion of an unsigned short int value of 50000 to a signed short int results in a value of -15,536."

不足为奇的是,将 said-value 发送到 std::cout 将为 said-value 的 signed short int 结果生成正确的输出。更改(转换)的来源很重要,在本例中它是实现定义的。他们的措辞很弱,identical 语句可以通过将 any 值分配给 any 整数值来应用,所以实际上他们的解释最终是 < em>毫无意义。


不想浪费之前的答案(在我更好地理解问题之前),享受一些轻松的阅读。要确定为什么会发生这种情况,您必须查阅您的实现文档以了解这种性质的转换。这可能不是您想要听到的答案,但背后有其原因。

发生这种情况是因为值(value)提升通过整数转换排名。实际上,您收到的值取决于实现,标准中涵盖了具体原因。

我将省略最基本的内容,直接进入正题:

C++11 §4.7 积分提升 [conv.integral]

  1. A prvalue of an integer type can be converted to a prvalue of another integer type. A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type.

  2. 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 ]

  3. If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

  4. If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one.

  5. The conversions allowed as integral promotions are excluded from the set of integral conversions.

值 50000 无法在您的平台上用 signed short int 表示。因此,结果是实现定义的。从它的外观来看,您的实现只是将字节从一个字节存储到另一个字节,结果是符号位(也包含在标准中但为简洁起见而省略)亮起并且报告的数字为负数。不过请记住,这是实现定义的,您不能在所有平台上都依赖此结果

关于c++ - signed/unsigned int 转换发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23070568/

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