# Compute the bit-length of an integer from bitwise shifts

I recently had to write a simple algorithm that computes the bit-length of an integer (the number of digits in the binary expansion of the integer) given only bitwise shifts and comparison operators. It is simple to compute the bit-length in linear time in the number of digits of the integer by computing the binary expansion and counting the number of digits, but it is also possible to do it in logarithmic running time in an upper bound for the bit-length of the integer. However, I wasn’t able to find such an algorithm described anywhere online so I share my solution here in case anyone else run into the same problem.

The idea behind the algorithm is to find the bit-length of an integer n \geq 0 using binary search with the following criterion: Find the unique m such that n \gg m = 0 but n \gg (m - 1) = 1 where \gg denotes a bitwise right shift. Note that m is the bit-length of n. Since the algorithm is a binary search, the running time is logarithmic in the maximal length of n.

Below are both a recursive and an iterative solution written in Java. They should be easy to translate to other languages.

### Recursive solution

public static int bitLength(int n, int maxBitLength) {
if (n <= 1) {
return n;
}
int m = maxBitLength >> 1;
int nPrime = n >> m;
if (nPrime > 0) {
return m + bitLength(nPrime, maxBitLength - m);
}
return bitLength(n, m);
}


### Iterative solution

public static int bitLength(int n, int maxBitLength) {
if (n <= 1) {
return n;
}
int length = 1;
while (maxBitLength > 1) {
int m = maxBitLength >> 1;
int nPrime = n >> m;
if (nPrime > 0) {
length += m;
n = nPrime;
maxBitLength = maxBitLength - m;
} else {
maxBitLength = m;
}
}
return length;
}