How to find index of first set bit

对着背影说爱祢 提交于 2020-01-14 14:45:28

问题


Is there bitwise solution to find the index of first set bit in mask with only one bit set? e.g. for 8 it would be 3, for 16 => 4 and so on. No loops plz. The best solution I can come up with is to createa map of bit to index.


回答1:


function firstBit(x) {
    return Math.floor(
        Math.log(x | 0) / Math.log(2)
    ) + 1;
}
i=4; console.log(i.toString(2), firstBit(i)); // 100 3
i=7; console.log(i.toString(2), firstBit(i)); // 111 3
i=8; console.log(i.toString(2), firstBit(i)); // 1000 4



回答2:


For posterity, ES6 introduced Math.log2 (and also log10) which does exactly that:

Math.log2(8) === 3

As a reminder, logA(x) is logB(x) / logB(A) for any A and B



来源:https://stackoverflow.com/questions/18134985/how-to-find-index-of-first-set-bit

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