根据标准,运算符 << 为第一个负符号操作数产生未定义行为。
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 按位包含或运算符
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 的补码或符号幅度的平台,那么在这些平台上的结果是什么?
最佳答案
按位运算独立地对每个位进行操作,无论每个位在被解释为数字类型的一部分时可能意味着什么。
所以是的,10000001 & 00000011 == 00000001
,无论每个位代表一个符号还是值的一部分。
关于c++ - C++中位运算符的定义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14260204/