This topic is now archived and is closed to further replies.


[java] good method of getting the least significant bit of a long?

Recommended Posts

EvilEd    122
Anyone know a fast method of getting the index of the lest sigificant bit of a long? Im currently using this quick hack of mine but it is way to slow in the long run.. :
private int lsb(long a){    
for(int i=63;i>0;i--){      
  if( (a & mask ) == mask[i] ){        
  return i;      }    }   
return 0;  }
mask[] is a vector of all the combinations.. like mask[0] = 0001, mask[1] = 00010, mask[3] = 00100 ... and so on. Anyone have any suggestions? :]

Share this post

Link to post
Share on other sites
tortoise    122
How does your method work? It starts from the top and finds the first bit that is set, isn't that the most significant bit?

Off the top of my head I'd try bitshifting instead of an array, that should be a bit quicker, something like

int lsb(long a)
int i;
for(i = 0; (a & 1) == 0 && i < 64; ++i)

a = a >> 1;

if(i == 64)
return -1;

return i;

but there's surely a trick that can be mustered up. Through a few negates and such I can get your number from say 1011...11000 to 0000...01000, but that doesn't quite help.

[edited by - tortoise on August 13, 2003 5:43:32 PM]

Share this post

Link to post
Share on other sites