根据标准,运算符 << 为带负号的第一个操作数产生未定义行为。
C++11 5.8.2
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 按位包含 OR 运算符
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;
使用 2 的补码,a 是 1111 1111,b 是 0000 0011。最后 c 等于 0000 0011 (+3)。
使用 1 的补码,a 是 1111 1110,b 是 0000 0011。c 等于 0000 0010 (+2) 吗?
使用符号大小,a 是 1000 0001,b 是 0000 0011。c 是否等于 0000 0001 (+1) ?
如果您可以使用 1 的补码或符号幅度访问平台,那么这些平台上的结果是什么?