Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible results of integer xor in C++

Is it guaranteed that (2 ^ 32) == 34?

like image 749
BeeOnRope Avatar asked Dec 03 '22 18:12

BeeOnRope


1 Answers

In C++20, yes.

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

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.

And [basic.fundamental] covers what a base-2 representation means:

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.

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.

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".

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).

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.

So:

In C++11, YMMV.

like image 145
Lightness Races in Orbit Avatar answered Dec 21 '22 23:12

Lightness Races in Orbit