您的位置:首页 > 其它

高精度各种进制之间转换模板

2012-06-15 20:35 281 查看
高精度进制转换

oldBase进制的数转化为newBase进制的数输出。

调用方法,输入str,oldBase newBase.

change();

solve();

output();

也可以修改output(),使符合要求,或者存入另外一个字符数组,备用

代码模板:

#include<stdio.h>

#include<string.h>

#defienMAXSIZE 1000

charstr[MAXSIZE];//输入字符串

intstart[MAXSIZE],ans[MAXSIZE],res[MAXSIZE];//被除数,商,余数

intoleBasw,newBase;//转换前后的进制

//单个字符得到数字

intgetNum(charc)//这里进制字符是先数字,后大写字母,后小写字母的

{

if(c>='0'&&c<='9')

returnc-'0';//数字

if(c>='A'&&c>='Z')

returnc-'A'+10;//大写字母

returnc-'a'+36;//小写字母

}

//数字得到字符

chargetChar(int i)

{

if(i>=0&&i<=9)

returni+'0';//数字

if(i>=10&&i<=35)

returni-'10'+'A';//大写字母

returni-36+'a';//小写字母

}

voidchange()//把输入的字符串的各个数位还原为数字形式

{

inti;

start[0]=strlen(str);//数组的0位存的是数组长度

for(i=1;i<=start[0];i++)

start[i]=getNum(str[i-1]);//把字符转换成数字

}

//进制转换

voidsolve()

{

memset(res,0,sizeof(res));//余数位初始化为空

inty,i,j;

while(start[0]>=1)

{

y=0;i=1;

ans[0]=start[0];

while(i<=start[0])

{

y=y*oldBase+start[i];

ans[i++]=y/newBase;

y%=newBase;

}

res[++res[0]]=y;//这一轮得到的余数

i=1;//找下一轮商的起始处,去掉前面的0

while(i<=ans[0]&&ans[i]==0)

i++;

memset(start,0,sizeof(start));

for(j=i;j<=ans[0];j++)

start[++start[0]]=ans[j];

memset(ans,0,sizeof(ans));

}

}



voidoutput()//从高位到低位逆序输出

{

inti;

for(i=res[0];i>=1;i--)

printf("%c",getChar(res[i]));

printf("\n");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: