Number of unset bit left of most significant set bit?

匿名 (未验证) 提交于 2019-12-03 08:42:37

问题:

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!