任意进制转化

#include<string>
#include<cstdio>
#include<iostream>
using namespace std;
void main()
{

	string b;
	string st[4];
	int i,p,m,n,K,t=0,L;
    int k[10][2];
	while(cin>>K>>b>>L){
		k[t][0]=K;
		st[t]=b;
		k[t][1]=L;
		t++;
	}
	for(int y=0;y<t;y++){
		
		
		p=1,n=0;
		m=st[y].length();
		string q=st[y];
		for(i=m-1;i>=0&&k[y][0]!=16;i--)
		{
			n+=(q[i]-48)*p;
			p*=k[y][0];
		}
		if(!n)
			for(i=m-1;i>=0;i--)
			{
				if(q[i]<65) n+=(q[i]-48)*p;
				if(q[i]>=65) n+=(q[i]-55)*p;
				p*=k[y][0];
			}
		
			
		if(k[y][1]==10){
			cout<<n<<endl;
		}else{
			int b1=0;
			int n1=n;
		  while(n1!=0){
			n1=n1/k[y][1];
			b1++;
			
		  }
		 short a[100];

		 for(int j=b1-1;j>=0;j--){
			a[j]=n%k[y][1];
			n=n/k[y][1];
		 }
		
		 for(j=0;j<b1;j++){
		  if(a[j]<10) cout<<a[j];
		  if(a[j]>=10){
		   if (a[j]==10) a[j]='A';
		   if (a[j]==11) a[j]='B';
		   if (a[j]==12) a[j]='C';
		   if (a[j]==13) a[j]='D';
		   if (a[j]==14) a[j]='E';
		   if (a[j]==15) a[j]='F';
		   printf("%c",a[j]);   //这里要用%c,表示输出的是字符类型,你之前用%d,表示输出的是整数类型(所以这里字符类型会转成整数类型)
		  }
		 }

		 cout<<"\n";
		}

	}
}


思路:将源数字进制转化为十进制,再由十进制转化为目标进制

猜你喜欢

转载自blog.csdn.net/weixin_36708538/article/details/78634092