最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to find index of first set bit - Stack Overflow

programmeradmin2浏览0评论

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 e up with is to createa map of bit to index.

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 e up with is to createa map of bit to index.

Share Improve this question asked Aug 8, 2013 at 19:57 Denis NarushevichDenis Narushevich 896 bronze badges 2
  • No loops plz - I love seeing that kind of stipulation. Why do you dislike loops? – Ian Commented Aug 8, 2013 at 20:01
  • 1 With loops it's trivial) – Denis Narushevich Commented Aug 8, 2013 at 20:13
Add a ment  | 

2 Answers 2

Reset to default 5
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

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

发布评论

评论列表(0)

  1. 暂无评论