gpt4 book ai didi

c - C中的位运算

转载 作者:太空宇宙 更新时间:2023-11-04 06:39:40 25 4
gpt4 key购买 nike

我是位运算的新手。我有 AND、OR、XOR 和 2s complement 的基本概念。但是我遇到了以下代码并且无法弄清楚输出。

char c1 = 0xFF; // -1
int shifted = c1 << 8; //-256 (-1 * 256)
printf("%d, %x\n", shifted, shifted);

int myInt;
myInt = 0xFFFFFFE2;
printf("%d\n", myInt);

int i = 0xff;
printf("%d\n", i<<2);

输出是:

-256, ffffff00
-30
1020

请帮助我了解这里发生了什么!

最佳答案

char c1 = 0xFF; // -1
int shifted = c1 << 8; //-256 (-1 * 256)

c1 被提升为 int 进行移位,所以它仍然是 -1,移位负 int 是实现定义的,但是你的实现似乎最喜欢并将它移位,就好像它是一个 unsigned 位模式,所以左移八位就是乘以 256。

printf( "%d, %x\n", shifted, shifted );
-256, ffffff00

如预期。 -256 的二进制补码位模式是 0xFFFFFF00(32 位 ints)。

int myInt;
myInt = 0xFFFFFFE2;

该位模式是 -30 的补码

printf("%d\n",myInt);

int i = 0xff ;

这是 255, 255*4 = 1020

printf("%d\n", i<<2);

-30
1020

关于c - C中的位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10254433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com