An Approach to Implement Log2 Lower Bound Function

If we consider the binary representation of numbers, we could find that the result of log2(n)\log_2(n) is actually related to the position of the first appearance of 11 in the binary bits. Let’s see some example below:

(7)dec=(0111)bin(8)dec=(1000)bin(13)dec=(1101)bin\begin{align} (7)_{dec} &= (0111)_{bin} \\[1em] (8)_{dec} &= (1000)_{bin} \\[1em] (13)_{dec} &= (1101)_{bin} \end{align}

For any positive integer nn, we have the following relationship:

log2(n)=IndexOfFirstOneBit(n)1\log_2(n) = \text{IndexOfFirstOneBit}(n) – 1
#include <iostream>

using std::cout, std::endl;

unsigned log2LowerBound(unsigned long long number)
{
    // records the MSB where the first 1 occurred in binary representation
    unsigned firstPosition = 0;
    // record the current index
    unsigned currentIdx = 0;

    while (number > 0)
    {
        if (number & 1)
        {
            firstPosition = currentIdx;
        }
        number >>= 1;
        ++currentIdx;
    }

    return firstPosition;
}

int main()
{
    for (int i = 0; i < 17; ++i)
    {
        cout << "log2 lower bound of " << i << " is: " << log2LowerBound(i) << endl;
    }
    return 0;
}

Published by Oyasumi

Just a normal person in the world

Leave a Reply

Your email address will not be published. Required fields are marked *