C++ c+中的基变换算法+/C

C++ c+中的基变换算法+/C,c++,C++,我有以下功能: template <class T> T c_base (T num,T second, T first = 10) { T res = 0; T secnum; T bitseed[90]; int i = 1,k,jump,anex,len; if(second==first) { res = num; return (res); } if(first==10&

我有以下功能:

template <class T>
T c_base (T num,T second, T first = 10)
{
    T res = 0;
    T secnum;
    T bitseed[90];
    int i = 1,k,jump,anex,len;
    if(second==first)
    {
        res = num;
        return (res);
    }
    if(first==10&&second!=10)
    {
        anex = num;
        while(num>0)
        {
            jump = num/second;
            bitseed[i] = num%second;
            num/=second;
            i++;
        }
        if(anex>0)
        {
            for(k=i;k>=1;k--)
            {
                if(k==i&&jump==0) {res = bitseed[k-1]; k--; continue;}
                if(k==i&&jump!=0) {res = jump; continue;}
                res = res*10+bitseed[k];
            }
        }
        return (res);
    }

    if(second==10)
    {
        anex = num;
        len = 1;
        while(anex>=10)
        {
            len *= 10;
            anex/=10;
            i++;
        }
        anex = num;
        if(anex>0)
        {
            for(k=i;k>=1;k--)
            {
                res = res*first+anex/len;
                anex%=len;
                len/=10;
            }
        }
        return (res);
    }

    if(second!=10&&first!=10)
    {
        secnum = c_base <T> (num,10,first);
        res = c_base <T> (secnum,second,10);
        return (res);
    }
}
模板
T c_基(T num,T second,T first=10)
{
T res=0;
T secnum;
T位种子[90];
int i=1,k,跳跃,anex,len;
如果(第二个==第一个)
{
res=num;
返回(res);
}
如果(第一个==10和第二个!=10)
{
anex=num;
while(num>0)
{
跳跃=数/秒;
比特种子[i]=num%秒;
num/=秒;
i++;
}
如果(anex>0)
{
对于(k=i;k>=1;k--)
{
如果(k==i&&jump==0){res=bitseed[k-1];k--;continue;}
如果(k==i&&jump!=0){res=jump;continue;}
res=res*10+比特种子[k];
}
}
返回(res);
}
如果(秒==10)
{
anex=num;
len=1;
而(anex>=10)
{
len*=10;
anex/=10;
i++;
}
anex=num;
如果(anex>0)
{
对于(k=i;k>=1;k--)
{
res=res*第一次+anex/len;
anex%=len;
len/=10;
}
}
返回(res);
}
如果(第二个!=10和第一个!=10)
{
secnum=c_base(num,10,first);
res=c_base(secnum,second,10);
返回(res);
}
}
我想知道它的效率有多高(从速度和内存消耗的角度来看),以及如何/如果可以改进它。(从算法角度)


Ps.功能说明:c_base(“数字”、“到基”、“从基”->可选)

我在这里看到了很多困惑:

  • 数字没有基数。我们的基础是数字表示法。输入和输出都应该是数字表示(例如C++中的
    std::strings
  • 为什么要特别对待10号底?它没有什么特别之处,只是因为历史上的偶然,今天大多数人都使用它。这与算法完全无关。由于技术原因(因为计算机内部使用BASE2),两个base的功率的特殊情况可能是有意义的
  • 为什么要进行双重转换,而不是只从基
    x
    读取数据,然后写入基
    y

因此不是代码审查的地方。您应该考虑如何在不经过基数10的情况下直接从基数K转换为基数N——可能还需要基数2^32或基数2^64……因为C什么时候有模板了?o、 OTake this to@WhozCraig谢谢你的建议…不知道有专门的论坛:)。我做了双重转换,因为我用来改变基数的算法只能从基数10变为x,从x变为10。但我会努力把事情弄清楚的。我对其他几点没有“借口”: