javascriptbit-manipulationbitwise-operatorsbit-shiftpersistent-data

What's the fastest way to calculate log of a power of 32?


Given that the language is javascript, and that the input is < 1073741824, what's the fastest way to obtain the equivalent to:

Math.floor(Math.log(len) / Math.log(32))

I've tried with an if:

if (len < 1024) return 1;
if (len < 32768) return 2;
if (len < 1048576) return 3;
if (len < 33554432) return 4;
if (len < 1073741824) return 5;

and with bitwise operators:

// 0000000000000000000000000100000 // 32
// 0000000000000000000010000000000 // 1024
// 0000000000000001000000000000000 // 32768
// 0000000000100000000000000000000 // 1048576
// 0000010000000000000000000000000 // 33554432
// 1000000000000000000000000000000 // 1073741824
function log32(len) {
    return (
        0 + 
        !!(len >>> 30) + 
        !!(len >>> 25) + 
        !!(len >>> 20) + 
        !!(len >>> 15) + 
        !!(len >>> 10) +
        !!(len >>> 5
    )
}

is there a way to do this cleaner or with less ops? (performance measured with: https://jsperf.com/log32-perf/)


Solution

  • I would go for the very efficient Math.clz32 method, which returns the number of leading zero bits in the 32-bit binary representation of a number.

    const log32 = x => Math.floor((31 - Math.clz32(x))/5);
    
    console.log(log32(1023)); // 1
    console.log(log32(1024)); // 2

    This will return the correct value for any x > 0 within the 32-bit range.