gpt4 book ai didi

c - 试图从标准中理解有符号整数转换规则

转载 作者:行者123 更新时间:2023-12-01 14:19:55 25 4
gpt4 key购买 nike

试图理解标准中的语法:

6.3.1.3 Signed and unsigned integers

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
  3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

注意 2 部分,这意味着将 int 转换为 unsigned int 是通过添加 UINT_MAX + 1 来执行的到 int 中的值。

例如在这两个讨论中讨论的内容:

Can a C compiler change bit representation when casting signed to unsigned?

Signed to unsigned conversion in C - is it always safe?

好吧,因为 UINT_MAX + 1 总是 promise 为零 ( https://stackoverflow.com/a/14899158/2162550 ) 2 部分可以读作:

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting zero until the value is in the range of the new type.

这对我来说毫无意义,因为添加零不会改变任何东西。我的英文翻译坏了吗?我在这里缺少什么?

最佳答案

  1. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

在此上下文中,“加法或减法”是指对数学 值进行运算,而不是使用 C 的 +- 对 C 值进行运算> 运营商。

例如,如果起始值为-42UINT_MAX65535,则结果为-42 + 65536 ,或 65494。此数学值在 unsigned int 的范围内,产生 65494U 的 C 值。

C 表达式 UINT_MAX + 1 的计算结果确实为零。这就是为什么该标准提到“比新类型可以表示的最大值多一个”而不是 UINT_MAX + 1。 (诚​​然,它可以说得更清楚一点。)

关于c - 试图从标准中理解有符号整数转换规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56982080/

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