gpt4 book ai didi

c - 右移运算符无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:37 24 4
gpt4 key购买 nike

为什么这段代码会进入死循环?

虽然它可以在其他机器上运行。该机器也是“小端”。它将继续打印 -1 值;

void printfbit(int n)
{
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n = n >> 1;
printf("\t %d\n",n);
}
//printf("\n");
}

最佳答案

来自 C 标准(参见第 6.5.7 节位移运算符):

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

您在无限循环中看到的行为是由于该特定实现的右移语义:右移有符号整数会保留符号位。

因此,对于任何负输入,您最终将以 0xffffffff... (== -1) 结束,并且将始终满足继续循环的条件。

一个例子:

原始输入: 0x80000000
一类后: 0xC0000000
两类后: 0xE0000000
三类倒后:0xF0000000
四类后: 0xF8000000
等等

关于c - 右移运算符无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31515524/

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