按位运算可移植吗?
Are bitwise operations portable?
假设我们有以下代码:
int j = -1 & 0xFF;
j
中的结果值可能是基于底层表示的以下值之一:
System Value
Two's complement 0xFF
One's complement 0xFE
Sign/Magnitude 0x01
但是 C 中的 &
、|
和 ^
运算符是否总是根据二进制补码定义的(从而使 j
始终等于 0xFF
), 或者它们是根据系统的底层表示来定义的?
它们是根据实际位表示定义的。来自 C11 final draft:
The result of the binary & operator is the bitwise AND of the operands (that is, each bit in the result is set if and only if each of the corresponding bits in the converted operands is set).
...
The result of the ^ operator is the bitwise exclusive OR of the operands (that is, each bit in the result is set if and only if exactly one of the corresponding bits in the converted operands is set).
...
The result of the | operator is the bitwise inclusive OR of the operands (that is, each bit in the result is set if and only if at least one of the corresponding bits in the converted operands is set).
假设我们有以下代码:
int j = -1 & 0xFF;
j
中的结果值可能是基于底层表示的以下值之一:
System Value
Two's complement 0xFF
One's complement 0xFE
Sign/Magnitude 0x01
但是 C 中的 &
、|
和 ^
运算符是否总是根据二进制补码定义的(从而使 j
始终等于 0xFF
), 或者它们是根据系统的底层表示来定义的?
它们是根据实际位表示定义的。来自 C11 final draft:
The result of the binary & operator is the bitwise AND of the operands (that is, each bit in the result is set if and only if each of the corresponding bits in the converted operands is set).
...
The result of the ^ operator is the bitwise exclusive OR of the operands (that is, each bit in the result is set if and only if exactly one of the corresponding bits in the converted operands is set).
...
The result of the | operator is the bitwise inclusive OR of the operands (that is, each bit in the result is set if and only if at least one of the corresponding bits in the converted operands is set).