gpt4 book ai didi

c - c中的左移位

转载 作者:太空狗 更新时间:2023-10-29 14:57:09 25 4
gpt4 key购买 nike

我一直在做一些关于位操作的愚蠢测试,我发现了这个问题。我执行这段代码:

int main(){
unsigned int i;
for (i=1; i<34; i++)
{
unsigned long temp = i;
unsigned long mul = 1;
unsigned long val;
unsigned long one = 1;

// Way 1
while (temp--)
mul = mul << one;

// Way 2
val = (one<<i);

printf(" \n 1<<%i \n mul: 0x%X , val: 0x%X\n",i, mul, val);
}
}

我当然知道当i>31的时候会产生溢出。我认为代码的两部分(way1 和 way2)应该输出相同的结果。但我明白了(最后):

 /* ... correct results from i=1 to i=31 ... */
1<<30
mul: 0x40000000 , val: 0x40000000

1<<31
mul: 0x80000000 , val: 0x80000000

1<<32
mul: **0x0** , val: **0x1**

1<<33
mul: **0x0** , val: **0x2**

为什么如果两条指令都是左移,程序会产生不同的输出?似乎部分 way2 产生了一个轮类,但我不知道为什么,我真的认为“mul”总是得到正确的值。

我在 Intel 32 位机器下编译,gcc 版本 4.4.7

最佳答案

可能是因为这是未定义的行为?根据 §6.5.7:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

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

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