-1

My question is simply: What is the most efficient way of finding both the number of leading zeros (zeros before the first set bit) and the number of trailing zeros (zeros after the last set bit) in an unsigned 32-bit integer?

So far I have found this solution, but I was wondering if anyone know of faster solutions. I also know there is an efficient way of doing it in c++.

Community
  • 1
  • 1
  • There's no builtin to do it, you'll have to do it manually. Have a look [here](http://stackoverflow.com/q/671815/1048572) (and at its linked questions) for inspiration. – Bergi Dec 14 '16 at 19:36

1 Answers1

0

After doing some more research I found this C solution, which I then translated to Javascript like so:

Code in C (returns the position from the right of the most significant bit):

static const char LogTable256[256] = 
{
#define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
    -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
    LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6),
    LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7)
};

unsigned int v; // 32-bit word to find the log of
unsigned r;     // r will be lg(v)
register unsigned int t, tt; // temporaries

if (tt = v >> 16)
{
  r = (t = tt >> 8) ? 24 + LogTable256[t] : 16 + LogTable256[tt];
}
else 
{
  r = (t = v >> 8) ? 8 + LogTable256[t] : LogTable256[v];
}

Code in Javascript (returns the number of leading zeros):

//http://graphics.stanford.edu/~seander/bithacks.html
//Translated from C
var logTable256 = [-1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
                   4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
                   5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
                   6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
                   6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7,
                   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
                   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
                   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
                   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
                   7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7];
Number.prototype.leadingZeros = function() {
    var r, t, tt;
    if (tt = this >>> 16) {
        r = (t = tt >>> 8) ? 24 + logTable256[t] : 15 - logTable256[tt];
    }
    else {
        r = (t = this >>> 8) ? 8 + logTable256[t] : 31 - logTable256[this];
    }
    return r;
}

This is about twice as fast as the method in the original question.