Fast way to convert a binary number to a decimal number

前端 未结 5 1622
感情败类
感情败类 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:09

    Since C++11 (even if C++11 is more limited than C++14 in that regard), function can be constexpr so avoid necessity of template to have compile time value.

    Here a version C++14 compatible:

    constexpr unsigned binary_to_decimal(unsigned num)
    {
        unsigned res = 0;
    
        while (num)
        {
            res = 10 * res + num % 10;
            num /= 10;
        }
        return res;
    }
    

    And for literals, you can even use binary literals since C++14:

    0b1010'1010 // or 0b10101010 without separator
    

提交回复
热议问题