快速的方法来二进制数转换为十进制数 [英] Fast way to convert a binary number to a decimal number

查看:309
本文介绍了快速的方法来二进制数转换为十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要转换例如像 unsigned int类型bin_number = 10101010 成十进制再presentation(即 170 )尽可能快地?最好的算法是什么?

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? What is the best algorithm?

推荐答案

使用模板,您可以在解决这个问题的编译时间

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; };

二进制模板,再次用实例化一个较小的 NUM ,直到 NUM 达到零和专业化作为终止条件。

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

例如:的std ::法院LT&;&LT;二进制&LT; 10101010&GT; ::值;

有关的运行时的问题:

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;
}

这篇关于快速的方法来二进制数转换为十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆