C ++中整数xor的可能结果 [英] Possible results of integer xor in C++

查看:69
本文介绍了C ++中整数xor的可能结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

在C ++ 20中,是的.

以下是 [expr.xor] 的定义方式:

Here's how [expr.xor] defines it:

给出以2为底的表示形式的系数 x i y i ([basic.fundamental ])转换后的操作数 x y ,则基数2的基数表示形式的系数 r i 如果 x i y i 中的一个(但不是全部),结果 r 为1 em>为1,否则为0.

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表示的含义:

宽度为 N 的无符号整数类型的每个值 x 具有唯一的表示形式 x = x 0 2 0 + x 1 2 1 +… + x N-1 2 N-1 ,其中每个系数 x i 为0或1;这称为 x base-2表示形式.有符号整数类型的值的以2为基数的表示形式是相应的无符号整数类型的全等值的以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是完全定义好的.

In short, it doesn't really matter how it's done "physically": the operation must satisfy the more abstract, arithmetic notion of base-2 (whether this matches the bits in memory or not; of course in reality it will) and so XOR is entirely well-defined.

但是,并非总是如此.该措辞由 P1236R1 引入,可以使整数运算清晰明了,并可以抽象出位"的概念.

However, this was not always the case. The wording was introduced by P1236R1, to make it crystal clear how integer operations behave and to abstract away the kind of wooly notion of a "bit".

在C ++ 11中,我们所知道的是带符号的整数必须遵循"使用二进制数字0和1的整数的位置表示,其中连续位表示的值是加法的,从1开始,并乘以连续的2的整数次幂,除了可能具有最高位置的位之外"(脚注49;请注意,这是非规范性的).

In C++11, all we knew is that signed integers must follow "A positional representation for integers that uses the binary digits 0 and 1, in which the values represented by successive bits are additive, begin with 1, and are multiplied by successive integral power of 2, except perhaps for the bit with the highest position" (footnote 49; be advised that this is non-normative).

实际上,这为我们提供了大部分途径,但是[expr.xor]中的特定措辞却不存在:我们所知道的是结果是操作数的按位异或功能" em>.在此关头,是否指的是充分理解的操作,实际上取决于您.请注意,您将很难找到关于允许执行此操作的不同意见.

This gets us most of the way there, actually, but the specific wording in [expr.xor] wasn't there: all we knew is that "the result is the bitwise exclusive OR function of the operands". At this juncture, whether that refers to a sufficiently commonly understood operation is really up to you. You'll be hard-pressed to find a dissenting opinion on what this operation was permitted to do, mind you.

所以:

在C ++ 11中,是YMMV.

这篇关于C ++中整数xor的可能结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆