Fast way to convert a binary number to a decimal number

Using templates you can solve this problem at compile-time.

template<unsigned long num>
struct binary
{
    static unsigned const value =
        binary<num/10>::value << 1 | num % 10;
};

// Specialization for zero
template<>
struct binary<0>
{ static unsigned const value = 0; };

The binary template is instantiated again with a smaller num, until num reaches zero and the specialization is used as a termination condition.

Example: std::cout << binary<10101010>::value;

For run-time problem:

unsigned binary_to_decimal(unsigned num)
{
    unsigned res = 0;

    for(int i = 0; num > 0; ++i)
    {
        if((num % 10) == 1)
            res += (1 << i);

        num /= 10;
    }

    return res;
}

Well, if this "number" is actually a string gotten from some source (read from a file or from a user) that you converted into a number (thinking it to be more appropriate for an actual number), which is quite likely, you can use a std::bitset to do the conversion:

#include <bitset>

unsigned int number = std::bitset<32>("10101010").to_ulong();

(Of course the 32 here is implementation-defined and might be more appropriately written as std::numeric_limits<unsigned int>::digits.)

But if it is really a number (integer variable) in the (very) first place you could do:

#include <string>

unsigned int number = std::bitset<32>(std::to_string(bin_number)).to_ulong();

(using C++11's to_string) But this will probably not be the most efficient way anymore, as others have presented more efficient algorithms based on numbers. But as said, I doubt that you really get this number as an actual integer variable in the very first place, but rather read it from some text file or from the user.

Tags:

C++

Binary