Fast way to convert a binary number to a decimal number

前端 未结 5 1623
感情败类
感情败类 2021-02-05 17:29

I have to convert a binary number like for example unsigned int bin_number = 10101010 into its decimal representation (i.e. 170) as quickly as possible

5条回答
  •  既然无缘
    2021-02-05 18:26

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

    template
    struct binary
    {
        static unsigned const value =
            binary::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;
    }
    

提交回复
热议问题