假设我们有以下代码:
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).
关于c - 按位运算可以移植吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39583194/