0

为什么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);
4

2 回答 2

3

在循环的最后一次迭代中,i是 11,但第 11 位x已经是 0,所以结果是 0x4567。我不知道你为什么期待别的东西。在 的情况下,您在 的前一个值中x &= ~(1 << i)清除了一点,而您继续为... 分配一个新值,一种情况是累积的,另一种不是。xx_tempx_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 的值, ...

于 2012-10-08T09:50:38.113 回答
2

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

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

是相同的

x_temp = x & ~(1 << 11);
于 2012-10-08T09:49:12.280 回答