gpt4 book ai didi

c - 在 C 中链接移位运算符后出现意外结果

转载 作者:行者123 更新时间:2023-12-01 22:21:53 25 4
gpt4 key购买 nike

我不明白为什么链接移位操作返回的结果与不链接它们的结果不同。

#include <stdio.h>

void bit_manip_func(unsigned char byte)
{
unsigned char chain = (((byte >> 3) << 7) >> 3);
printf("%d\n", chain); //this prints 144

unsigned char o1 = byte >> 3;
unsigned char o2 = o1 << 7;
unsigned char o3 = o2 >> 3;
printf("%d\n", o3); //this prints 16 as expected
}

int main()
{
//expecting both printf's to print
//the same value (16).
bit_manip_func(73);
return 0;
}

我期待两者 printf调用打印出 16,因为二进制中的 73 是 0100 1001。应用 byte >> 3 后我应该在 (byte >> 3) << 7 之后得到 0000 1001结果应该是 1000 0000,在 (((byte >> 3) << 7) >> 3) 之后结果应该是 0001 0000,当然是 16。实际发生了什么?

最佳答案

运算符>> 和<< 对其操作数执行整数提升。因此,当与任一运算符一起使用时,类型 unsigned char 被提升为 int。

在下面一行中,变量 byte 被提升为 int 类型,然后所有三个操作都在该类型上执行:

unsigned char chain = (((byte >> 3) << 7) >> 3);

因此保留设置为 1 的最左边的位:

01001001 => 01001 => 010010000000 => 010010000 
^ ^ ^ ^

在下面的代码中,变量被提升为 int 类型,但在每次操作之后,具有 int 类型的结果被分配给一个 unsigned char 并因此换行(最高有效位被删除),
因为在您的平台上 unsigned char 的范围是 [ 0 , 2^8-1 ]。

unsigned char o1 = byte >> 3;
unsigned char o2 = o1 << 7;
unsigned char o3 = o2 >> 3;

这意味着设置为 1 的最左边的位不会被保留:

01001001 => 01001 => 10000000 => 000010000
^ ^

关于c - 在 C 中链接移位运算符后出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39466157/

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