Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the functionalities of two lines of code

Tags:

c++

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.

like image 706
user297850 Avatar asked Jul 27 '10 15:07

user297850


2 Answers

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.

like image 86
Eclipse Avatar answered Oct 24 '22 04:10

Eclipse


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.

like image 43
Justin Ethier Avatar answered Oct 24 '22 03:10

Justin Ethier