Rasmi Ranjan Nayak
Rasmi Ranjan Nayak

Reputation: 11948

Why this code is not working as per intended

Why x_temp is not updating the value, where as the commented line x &= ~(1 << i); is working perfectly. Where it is going wrong?

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);

Upvotes: 0

Views: 86

Answers (2)

Jim Balter
Jim Balter

Reputation: 16406

In the last iteration of your loop, i is 11, but the 11th bit of x is already 0, so the result is 0x4567. I don't know why you expect something else. In the case of x &= ~(1 << i), you clear a bit in the previous value of x, whereas with x_temp you keep assigning a fresh value to x_temp ... one case is cumulative, the other is not.

Consider a trace of the two loops:

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

but

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)

Maybe this is clearer: Suppose x = 5; then a loop that sets x += 1 will yield values of 6,7,8,9,10, ... but a loop that sets x_temp = x + 1 will yield values of 6,6,6,6,6,...

Upvotes: 3

Zeta
Zeta

Reputation: 105876

Maybe it's because you're discarding the old values of x_temp?

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

is the same as

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

Upvotes: 2

Related Questions