c - 按位运算可以移植吗?

标签 c language-lawyer bitwise-operators

假设我们有以下代码:

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/

相关文章:

c - 通过来自其他结构成员的偏移指针访问结构成员是否合法?

javascript - 使用枚举限制的按位运算获得反向

(int)Math.pow(2,x) 和 1<<x 的 Java 结果不同

c - 如何在 switch 与 integer using 中使用枚举

c - 将 char* 传递给结合 memcpy 的函数

COMDAT 与 BSS 定义

c++ - C++ 数组上指针数学的未定义行为

c - 从文件中删除字符串

c++ - 指针差异是否是在基于范围的 for 循环中查找 vector 中元素索引的有效方法?

c# - 将整数中的一位与另一位交换,代码不起作用