In direct C (long, long, 64 bits in my setup), taken from similar Java implementations: (updated after a bit more reading on the Hamming weight)
A bit more explanation: the top just sets all the bits to the right of the most significant 1, and then negates it. (i.e., all 0 in the "left" most significant 1s are now equal to 1, and everything else is 0).
Then I used Hamming Weight to count the bits.
unsigned long long i = 0x0000000000000000LLU; i |= i >> 1; i |= i >> 2; i |= i >> 4; i |= i >> 8; i |= i >> 16; i |= i >> 32; // Highest bit in input and all lower bits are now set. Invert to set the bits to count. i=~i; i -= (i >> 1) & 0x5555555555555555LLU; // each 2 bits now contains a count i = (i & 0x3333333333333333LLU) + ((i >> 2) & 0x3333333333333333LLU); // each 4 bits now contains a count i = (i + (i >> 4)) & 0x0f0f0f0f0f0f0f0fLLU; // each 8 bits now contains a count i *= 0x0101010101010101LLU; // add each byte to all the bytes above it i >>= 56; // the number of bits printf("Leading 0 = %lld\n", i);
I would be interested to see how effective it was. Tested it with multiple values, although it seems to work.
Dusty
source share