Getting bit length of a number

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
Shifting
function getBitLength(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
}
ready
Loop
function getBitLength(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;
}
ready

Revisions

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