Getting bit length of a number (v4)

Revision 4 of this benchmark created on


Description

Note: Only supports up to Uint32

Setup

function getBitLengthShifting(num) {
    let length = 0;
    
    if (num >= 1 << 16) { 
        num >>= 16; 
        length += 16;
    }
    if (num >= 1 << 8) { 
        num >>= 8; 
        length += 8;
    }
    if (num >= 1 << 4) { 
        num >>= 4; 
        length += 4;
    }
    if (num >= 1 << 2) { 
        num >>= 2; 
        length += 2;
    }
    if (num >= 1 << 1) { 
        length += 1;
    }

    return length + 1; // Add 1 to account for the last bit
}

function getBitLengthLooping(num) {
    if (num === 0) return 1; // Special case: 0 is represented by a single bit "0"
    
    let length = 0;
    while (num > 0) {
        num >>= 1; // Shift the number right by 1 bit
        length++;
    }
    return length;
}

function getBitLengthMath(num) {
    if (num === 0) return 1; // Special case: 0 is represented by a single bit "0"
    return Math.floor(Math.log2(num)) + 1;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Shifting
getBitLengthShifting(4294967295)
ready
Loop
getBitLengthLooping(4294967295)
ready
Math function
getBitLengthMath(4294967295)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.