首页 > 其他分享 >进制转换

进制转换

时间:2023-02-28 18:23:44浏览次数:24  
标签:转换 进制 moven int void cout string

 

1.8进制转16进制

string octs,hexs,t;
void OtoH(){
    for(int i=0;i<octs.length();i+=1){
        string s=octs.substr(i,1);
        if(s=="0")t+="000";
        if(s=="1")t+="001";
        if(s=="2")t+="010";
        if(s=="3")t+="011";
        if(s=="4")t+="100";
        if(s=="5")t+="101";
        if(s=="6")t+="110";
        if(s=="7")t+="111";
    }
    int len=t.length();
    for(int i=len;i>=0;i-=4){
        string s;
        if(i<4){
            for(int j=1;j<=4-i;j++){
                s+="0";
            }
        }
        s+=t.substr((i-4>=0)?i-4:0,(i<4)?i:4);
//      cout<<s<<'\n';
        hexs+=mp[s];
    }
}
void INIT(){
    mp["0000"]="0";
    mp["0001"]="1";
    mp["0010"]="2";
    mp["0011"]="3";
    mp["0100"]="4";
    mp["0101"]="5";
    mp["0110"]="6";
    mp["0111"]="7";
    mp["1000"]="8";
    mp["1001"]="9";
    mp["1010"]="A";
    mp["1011"]="B";
    mp["1100"]="C";
    mp["1101"]="D";
    mp["1110"]="E";
    mp["1111"]="F";
}

 

 

2.任意进制转十进制

void moven(string n,int p){
	int num=0;
	stack<int>s;
	if(n=="0")cout<<0;
	else{
		for(int i=0;i<n.length();i++){
			num*=p;
			if(n[i]>='0'&&n[i]<='9')num+=n[i]-'0';
			else num+=(n[i]-'A'+10);
		}
	}
	cout<<num<<'\n';
}

  

3.十进制转任意进制

void moven(int n,int p){
	stack<int>s;
	if(n==0)cout<<0;
	else{
		while(n){
			s.push(n%p);
			n/=p;
		}
	}
	while(s.size()){
		if(s.top()<10)cout<<s.top();
		else cout<<char(s.top()-10+'A');
		s.pop();
	}
	cout<<'\n';
}

  

4.任意进制转任意进制

int moven(string n,int p){
	int num=0;
	stack<int>s;
	if(n=="0")cout<<0;
	else{
		for(int i=0;i<n.length();i++){
			num*=p;
			if(n[i]>='0'&&n[i]<='9')num+=n[i]-'0';
			else num+=(n[i]-'A'+10);
		}
	}
	return num;
}
void movem(int n,int p){
	stack<int>s;
	if(n==0)cout<<0;
	else{
		while(n){
			s.push(n%p);
			n/=p;
		}
	}
	while(s.size()){
		if(s.top()<10)cout<<s.top();
		else cout<<char(s.top()-10+'A');
		s.pop();
	}
	cout<<'\n';
}

move(moven(number,n),m)

  

 

 

 

 

标签:转换,进制,moven,int,void,cout,string
From: https://www.cnblogs.com/zhanghx-blogs/p/17162269.html

相关文章