Javascript implementation of two common functions: bit population count (Hamming weight) and bit-length.
Update May 29th: Refactoring, improved signed vs. unsigned handling.
<script type="text/javascript">

/*

 Javascript bitLen / popCnt -  by Luigi Galli
 Bugs/Questions/Comments/Improvements? Mail me:
 LG@THLG.NL - http://thlg.nl?faultylabs

*/

/*
 bitLen(n)
 Returns the bit-length of n (that is: how many bits are required to represent n)
 n must be an unsigned integer in the range [0..(2^32)-1]
 Runs through 12 iterations at most
*/
function bitLen(n) {
    n >>>= 0 /* force uint32 */
    // quickly skip over the 1st 0 to 3 bytes, then scan the final byte
    // could be fully unrolled to avoid looping
    for (var baselen = 24; baselen >= 0; baselen -=8) {
        if ((0xFF << baselen) & n || !baselen ) {
            /* note below 1: no for body -- 2: the '&& len' is required in case the byte is = 0*/
            for (var len = 7; !((n >>> baselen) & (1 << len)) && len ; len--) ;
            return len + 1 + baselen
        }
    }
}

/*
  More compact (but slower) bitLen
  Runs through 31 iterations at most
*/
function bitLen2(n) {
    n >>>= 0 /* force uint32 */
    for (var L = 31; n < (1<<L)>>>0 && L; L--) ;  // note: unsigned conversion '>>>0' can be expensive
    return ++L  
}

/*
 popCnt(n)
 Returns the bit population count of n (that is: how many bits in n are set to 1)
 n must be an unsigned integer in the range [0..(2^32)-1]
 This lookup-table-free method is from Kernighan & Ritchie's "The C Programming Language"
 Exercise 2.9 (on page 62 of my copy). Not sure whether they (K&R) are the inventors.
*/
function popCnt(n) {
    n >>>= 0 /* force uint32 */
    for(var popcnt = 0; n; n &= n - 1) {
        popcnt++
    }
    return popcnt
}


// quick assertions test
alert(bitLen(0x1acfe557) == 29)
alert(bitLen(0)  == 1)
alert(bitLen(4095) == 12)

alert(bitLen2(0x1acfe557) == 29)
alert(bitLen2(0)  == 1)
alert(bitLen2(4095) == 12)

alert(popCnt(0) == 0)
alert(popCnt(0x55AA) == 8)
alert(popCnt(16777216) == 1)

</script>