Reputation: 8005
When I was trying to learn from an existing program, I could not understand what the following two lines of code try to do?
for(i=0;0==(x&1);++i)x>>=1;
if(0==(x-=y)) return y<<i;
Any explanations would be appreciated.
Upvotes: 5
Views: 193
Reputation: 208323
Will return x
if x
is y
left shifted an indeterminate i
number of positions.
That is, if x = 01010000
and y = 00000101
it will return x
. There is no info in the question to guess what it will return if the condition is not met.
Upvotes: 0
Reputation: 89729
Is this an interview question?
The << and >> operators and & as well are all bitwise operations.
Superficially, the first one seems to shift right until it finds a 1 bit, but is destructive.
The other one is quite convulted.
However, without more context it is not clear what the program is trying to do.
Upvotes: 0
Reputation: 45493
for(i=0;0==(x&1);++i)x>>=1
Finds the least significant bit set to 1
in an integer
if(0==(x-=y)) return y<<i;
Subtracts y
from x
, and if the result is 0, returns y
shifted over (toward the more significant bits) by i
bits.
Upvotes: 9
Reputation: 134167
for(i=0;0==(x&1);++i)x>>=1;
This code x>>=1
is shifting the bits of x
to the right one place. This will continue as long as 0==(x&1)
is true, which means that the right-most bit of x
is a 0. i
is the number of bits shifted.
if(0==(x-=y)) return y<<i;
This code subtracts y
from x
. Then, if x
is 0 the code returns y
shifted to the left by i
bits.
Upvotes: 4