Luc*_*cas 1 c++ printf bitwise-operators integer-promotion
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned char a=100,b=50;
printf("%d & %d = %d\n",a,b,a&b);
printf("%d | %d = %d\n",a,b,a|b);
printf("%d ^ %d = %d\n",a,b,a^b);
printf(" ~%d = %d\n",a, ~a); /*the out come of this line would be this: ~100 = -101 */
printf(" %d >> 2= %d\n",a, a>>2);
printf(" %d << 2= %d\n",a, a<<2);
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
/结果应该是 155,不是吗?/
根据标准, 的操作数~将进行积分提升。所以这里我们先将推广a到int.
[expr.unary.op] : ~ 的操作数应具有整型或无作用域枚举类型;结果是其操作数的补码。进行积分促销。
如果int是 4 个字节(例如),则提升的a值为0x00000064。的结果~a是0xFFFFFF9B,这正是-101(如果使用补码来表示整数)。
请注意,虽然可变参数会进行整体提升,但这里~a是类型int,不需要额外的提升。