There is no similar O (1) bitwise trick to find the value of a number. Many microprocessor sets contain special instructions for "counting leading zeros." There is no operator in the C language family that has given JavaScript its bit-by-bit functionality.
The only alternative to O (1) is to use Math.floor( Math.log( n ) / Math.LN2 ) Quick Test
for ( var i = 0; i == Math.floor( Math.log( 1<<i ) / Math.LN2 ); ++ i ) ;
gives i == 31 as a result, due to the << operator using 32-bit arithmetic, signed by two additions.
If you want to be a purist, you can repeatedly shift right by one, which is O (log n ), or you can repeatedly shift right by 16 >> i , for i from 0 to 4, rejecting shifts when the result is zero and in otherwise, 16 >> i accumulates. This is O (log log N), where N is the maximum possible value for n , which means constant time, but in all likelihood slower than Math.log .
Code for O (log log N) algo:
var mag = function( n ) { var acc = 0; for ( var i = 16; i; i >>= 1 ) { if ( n >> i ) { n >>= i; acc += i; } } return acc; };
Of course, for any of them, you need to shift left by the result to get the "leftmost 1-bit", not the index.
EDIT: Note. The log implementation returns -Infinity for zero, while the mag function returns 0 , which matches its result for 1 . If you want to take into account the possibility of the absence of a left 1-bit existing one, it is better to make it a special case.