Note that the largest unsigned 32-bit integer is 4294967295, which is 2^{32}-1. Hence, the integer binary logarithm cannot exceed 31 (i.e., 16 + 8 + 4 + 2 + 1), which corresponds to the bit sequence
00000000000000000000000000011111
Initialize a return variable with the value zero.
If at least one of the first sixteen most significant bits of the input 32-bit integer x is turned on, we know that the power to which the number 2 must be raised to obtain x is at least 16 (i.e., x > 65536). Hence, activate the corresponding bit of the return variable. Mutate x by shifting sixteen bits to the right, discarding the bits shifted off.
Carry out the following steps with B in [ 8, 4, 2, 1 ]:
If at least one of the next B most significant bits of the current x is turned on, we know that the power to which the number 2 must be raised to obtain x has to be increased by B.
Activate the bit of the return variable that corresponds to B.
Mutate x by shifting B bits to the right, discarding the bits shifted off.
The final value of the return variable is the integer binary logarithm of x.
Computes an integer binary logarithm (base two).
Method
Note that the largest unsigned 32-bit integer is
4294967295
, which is2^{32}-1
. Hence, the integer binary logarithm cannot exceed31
(i.e.,16 + 8 + 4 + 2 + 1
), which corresponds to the bit sequenceInitialize a return variable with the value zero.
If at least one of the first sixteen most significant bits of the input 32-bit integer
x
is turned on, we know that the power to which the number2
must be raised to obtainx
is at least16
(i.e.,x > 65536
). Hence, activate the corresponding bit of the return variable. Mutatex
by shifting sixteen bits to the right, discarding the bits shifted off.Carry out the following steps with
B
in[ 8, 4, 2, 1 ]
:B
most significant bits of the currentx
is turned on, we know that the power to which the number2
must be raised to obtainx
has to be increased byB
.B
.x
by shiftingB
bits to the right, discarding the bits shifted off.The final value of the return variable is the integer binary logarithm of
x
.