开发者

the functionalities of two lines of code

开发者 https://www.devze.com 2023-01-08 21:21 出处:网络
When I was trying to l开发者_JAVA百科earn from an existing program, I could not understand what the following two lines of code try to do?

When I was trying to l开发者_JAVA百科earn 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.


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消