为什么此代码无法按预期工作

时间:2012-10-08 09:46:03

标签: c bit-manipulation

为什么x_temp没有更新值,因为注释行x &= ~(1 << i);工作正常。 哪里出错?

int x = 0x4567;
int x_temp = 0x0;// = 0xF0FF;
int y = 0x0200;
int i;
for(i = 8; i < 12; i++)
{//clean clear
    x_temp = x & ~(1 << i);
    //x &= ~(1 << i); //This line works perfectly.
}
printf("x_temp = %x....\n", x_temp);//Still it retains the value 0x4567.
printf("x = %x....\n", x);
y = x|y; //y = x_temp|y;
printf("y = %x\n", y);

2 个答案:

答案 0 :(得分:3)

在循环的最后一次迭代中,i为11,但x的第11位已经为0,因此结果为0x4567。我不知道你为什么期待别的东西。在x &= ~(1 << i)的情况下,您在x之前值中清除一点,而使用x_temp时,您会为x_temp分配一个新值} ...一个案例是累积的,另一个案例不是。

考虑两个循环的痕迹:

for `x &= ~(1 << i)`, you have
x is 0x4567 originally
x is 0x4467 after clearing 1<<8
x is 0x4467 after clearing 1<<9
x is 0x4067 after clearing 1<<10
x is 0x4067 after clearing 1<<11
     

for `x_temp = x & ~(1 << i)`, you have
x is 0x4567 (originally and forever)
x_temp is 0x4467 after clearing 1<<8 from x (which hasn't changed)
x_temp is 0x4567 after clearing 1<<9 from x (which hasn't changed)
x_temp is 0x4167 after clearing 1<<10 from x (which hasn't changed)
x_temp is 0x4567, after clearing 1<<11 from x (which hasn't changed)

也许这更清楚: 假设x = 5;那么设置x + = 1的循环将产生6,7,8,9,10的值,...... 但设置x_temp = x + 1的循环将产生值6,6,6,6,6,...

答案 1 :(得分:2)

也许是因为您丢弃了x_temp的旧值?

for(i = 8; i < 12; i++)
{
    x_temp = x & ~(1 << i);
}

相同
x_temp = x & ~(1 << 11);