gpt4 book ai didi

c - 与左移运算符 (<<) 的结果不一致

转载 作者:行者123 更新时间:2023-12-02 18:01:28 26 4
gpt4 key购买 nike

我正在使用 C 学习位操作。我在编写将二进制转换为十进制的程序时遇到了问题,特别是在程序的 for 循环中。以下是我的代码:

unsigned int binary_to_uint(const char *b)
{
unsigned int result = 0;
int i, len;
if (!b)
return (0);
len = strlen(b);
for (i = 0; i < len; i++)
{
if (b[i] == '1')
{
result += 2 << (i-1); /*where my issue is*/
}
else if (b[i] == '0')
continue;
else
return (0);
}
return (9);
}

我试过调试,我意识到我的问题源于 if 语句

因此,我对 if* 语句中的代码做了一些实验:

int main() {
// Write C code here
int i = 0;
printf("result of 2 << (%d - 1): %d\n", i, 2 << (i - 1));
printf("result of 2 << (0 - 1): %d", 2 << (0 - 1));

return 0;
}

在第一个 printf 中,在控制台中显示 result of 2 << (0 - 1): 0,而在第二个 printf 中,在控制台中显示 result of 2 << (0 - 1): 1。我的期望是两个 printf 应该显示完全相同的东西,即 2 << -1 的值是 1,但事实并非如此。有人可以帮我理解发生了什么事吗?为什么使用变量 i 将移位运算符的结果更改为 0?

最佳答案

<< 的右侧操作数或 >>运算符必须是非负的。对此操作数使用负值会触发 undefined behavior .因此,您不能使用负值向相反方向移动。

这在 C standard 的第 6.5.7p3 节中有详细说明。 :

The integer promotions are performed on each of the operands. The typeof the result is that of the promoted left operand. If the value ofthe right operand is negative or is greater than or equal to the widthof the promoted left operand, the behavior is undefined.

在您的特定情况下,未定义的行为表现为使用 i-1 之间的不同结果。和 0-1为正确的操作数。

而不是转移 2通过 i-1地方,而不是转移 1通过 i地点:

result += 1 << i; 

关于c - 与左移运算符 (<<) 的结果不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74293486/

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