可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Assuming the 64bit integer 0x000000000000FFFF
which would be represented as
00000000 00000000 00000000 00000000 00000000 00000000 >11111111 11111111
How do I find the amount of unset bits to the left of the most significant set bit (the one marked with >) ?
回答1:
// clear all bits except the lowest set bit x &= -x; // if x==0, add 0, otherwise add x - 1. // This sets all bits below the one set above to 1. x+= (-(x==0))&(x - 1); return 64 - count_bits_set(x);
Where count_bits_set
is the fastest version of counting bits you can find. See https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel for various bit counting techniques.
回答2:
In straight C (long long are 64 bit on my setup), taken from similar Java implementations: (updated after a little more reading on Hamming weight)
A little more explanation: The top part ju