c++ - C++中整数异或的可能结果

标签 c++ c++11 language-lawyer

是否保证 (2 ^ 32) == 34

最佳答案

在 C++20 中,是的。

这是如何[expr.xor]定义它:

Given the coefficients xi and yi of the base-2 representation ([basic.fundamental]) of the converted operands x and y, the coefficient ri of the base-2 representation of the result r is 1 if either (but not both) of xi and yi are 1, and 0 otherwise.

[basic.fundamental]涵盖了 base-2 表示的含义:

Each value x of an unsigned integer type with width N has a unique representation x = x020 + x121 + … + xN-12N-1, where each coefficient xi is either 0 or 1; this is called the base-2 representation of x. The base-2 representation of a value of signed integer type is the base-2 representation of the congruent value of the corresponding unsigned integer type.

简而言之,它是如何“物理地”完成的并不重要:操作必须满足base-2的更抽象的算术概念(无论这是否与内存中的位匹配; 当然在现实中它会)所以 XOR 是完全定义好的。

然而,情况并非总是如此。措辞由P1236R1引入,以明确整数运算的行为方式并抽象出“位”的那种模糊概念。

在 C++11 中,我们所知道的是有符号整数必须遵循 “使用二进制数字 0 和 1 的整数位置表示,其中连续位表示的值是相加的,以 1 开头, 并乘以 2 的连续整数次方,可能位置最高的位除外”(脚注 49;请注意,这是非规范的)。

实际上,这让我们完成了大部分工作,但是 [expr.xor] 中的特定措辞并不存在:我们所知道的是 “结果是按位的操作数的异或功能”。在这个时候,这是否指的是一个足够普遍理解的操作真的取决于你。请注意,您很难就此操作被允许执行的操作找到不同意见。

所以:

在 C++11 中,YMMV。

关于c++ - C++中整数异或的可能结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589410/

相关文章:

c++ - 将货币金额四舍五入到最接近的五分之一、四分之一、1 美元、5 美元等面额的最佳方法是什么?

c++ - constexpr和const之间的区别

c - 在三元运算符中隐式转换为 void*?

c++ - vector 分配是否会使 `reserve` 无效?

c++ - 组合 ECDSA key

c++ - cef项目编译链接error2001

c++ - 为什么我的字节数组在我将它插入我的数据库时在 0x00 处拆分(SQL SERVER,C++)

multithreading - c++11线程编译错误

c++11 - 运算符 std::string() 上的 abi_tab:clang++ 和 g++ 中的不兼容

c++ - 重载运算符的德摩根定律优化