c++ - 在 C++20 中从有符号整数到无符号整数,反之亦然

标签 c++ language-lawyer signed twos-complement c++20

在 C++20 之前,不能保证有符号整数是二进制补码。现在我们有两篇论文提出将二进制补码标准化作为唯一表示:p0907p1236而且,如果我理解正确的话,其中一个已合并到 C++20 工作草案中。

那么,有符号到无符号的转换意味着什么,反之亦然?我看过 cppreference并发现了以下措辞:

If the destination type is unsigned, the resulting value is the smallest unsigned value equal to the source value modulo 2<sup>n</sup> where n is the number of bits used to represent the destination type.

If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is the unique value of the destination type equal to the source value modulo 2<sup>n</sup> where n is the number of bits used to represent the destination type. (Note that this is different from signed integer arithmetic overflow, which is undefined).

不幸的是,我无法理解这个措辞,我想知道 C++20 工作草案中写的是什么。

所以有两个问题:

  1. 语言律师部分:有人可以指出标准的确切内容以及它在标准中的什么位置吗?

  2. 有人可以用更通俗的术语解释该措辞,可能还解释模运算并提供示例吗?

最佳答案

转换规则为[conv.integral]/3 :

Otherwise, the result is the unique value of the destination type that is congruent to the source integer modulo 2<sup>N</sup>, where N is the range exponent of the destination type.

范围指数在 [basic.fundamental] 中的表中进行了描述,但意味着你所期望的(对于 int 它至少是 16,对于 long long ,它至少是 64,等等)。

例如,转换 short具有值(value) -3unsigned short就是找到类型的唯一值unsigned short这与 -3 一致模 2<sup>16</sup> ...也就是说,2<sup>16</sup>-365533 .但是转换相同的 short -3 的值至 unsigned long long会将模基数更改为 2<sup>64</sup> , 所以你最终得到 18446744073709551613相反。

从带符号类型转换为具有不同指数范围的带符号类型(或者同样将无符号类型转换为无符号类型)更为直接 - 您只需切掉位或对它们进行零扩展。转换 short值为 258 到 intlonglong long只是 258,但是到 signed char例如,是 2。

关于c++ - 在 C++20 中从有符号整数到无符号整数,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54947427/

相关文章:

c++ - noexcept(false) 析构函数覆盖所有特殊成员函数的异常规范?

谁能解释为什么下面的程序什么都不输出?

algorithm - 汇编中 x86 上的带符号 64 位乘法和 128 位除法

c++ - 在引用初始化中使用已删除的复制构造函数进行复制初始化

iphone - 是否可以在 iPhone 或 iPad 上查看数字签名的 pdf?

c++ - 通过不同的线程使用多个 ORB(多线程多 Orb 客户端应用程序) - 如何?

c++ - 嵌套类作为C++中成员函数的参数

c++ - 具有尾随返回类型的模板成员函数,即使未使用也会出错

c++ - 检测模板模板参数的实际参数

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