C++中按位运算符的定义是什么?

Arn*_*aud 3 c++ undefined-behavior language-lawyer

根据标准,operator <<为负签名的第一个操作数产生一个未定义的行为.

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
Run Code Online (Sandbox Code Playgroud)

这是可以理解的,因为内存中的整数布局是实现定义的.

C++ 11 3.9.1.7

this International Standard permits 2’s complement, 1’s complement and
signed magnitude representations for integral types.
Run Code Online (Sandbox Code Playgroud)

另一方面,标准似乎没有确切地定义什么是bitwise&| 和^应该这样做.

C++ 11 5.11按位AND运算符

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.
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

这些运营商的定义完全不适合我.它是标准中的其他地方吗?是否为有符号整数定义了结果实现?

举个例子,让我们来看看这段代码:

signed char a=-1;
signed char b=3;
signed char c=a&b;
Run Code Online (Sandbox Code Playgroud)

使用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的补码或符号幅度访问平台,那么这些平台的结果是什么?

Mik*_*our 5

按位运算独立地对每个位进行操作,无论每个位在解释为数字类型的一部分时可能意味着什么.

所以是的,10000001 & 00000011 == 00000001无论每个位代表一个符号还是一个值的一部分.