The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-
filled. If E1 has an unsigned type, the value of the result is E1 × 2 pow E2,
reduced modulo one more than the maximum value representable in the result type.
Otherwise, if E1 has a signed type and non-negative value, and E1 × 2 pow E2 is
representable in the result type, then that is the resulting value; otherwise,
the behavior is undefined
这是可以理解的,因为内存中整数的布局是由实现定义的。 C++11 3.9.1.7
this International Standard permits 2’s complement, 1’s complement and
signed magnitude representations for integral types.
另一方面,标准似乎并没有明确定义按位 & | 和 ^ 应该执行什么操作。
C++11 5.11 按位与运算符
and-expression:
equality-expression
and-expression & equality-expression
1 The usual arithmetic conversions are performed; the result is the bitwise
AND function of the operands. The operator applies only to integral
or unscoped enumeration operands.
C++11 5.12 按位异或运算符
exclusive-or-expression:
and-expression
exclusive-or-expression ˆ and-expression
1 The usual arithmetic conversions are performed; the result is the bitwise
exclusive OR function of the operands. The operator applies only to integral
or unscoped enumeration operands.
C++11 5.13 按位或运算符
inclusive-or-expression:
exclusive-or-expression
inclusive-or-expression | exclusive-or-expression
1 The usual arithmetic conversions are performed; the result is the bitwise
inclusive OR function of its operands. The operator applies only to integral
or unscoped enumeration operands.
这些运算符的定义完全使我懵逼了。它们是否在标准中有说明?对于有符号整数,结果是实现定义的吗?
举个例子,让我们看看这段代码:
signed char a=-1;
signed char b=3;
signed char c=a&b;
使用二进制补码,a为1111 1111,b为0000 0011。最终c等于0000 0011(+3)。
使用一进制补码,a为1111 1110,b为0000 0011。那么c是否等于0000 0010(+2)?
使用符号-数量表示法,a为1000 0001,b为0000 0011。那么c是否等于0000 0001(+1)?
如果您可以访问使用一进制补码或符号-数量表示法的平台,那么这些平台上的结果是什么?