进制的转化

十六进制转化为十进制

#include<stdio.h>
#include<iostream>
#include<stack>
#include<string>
#include<math.h>
using namespace std;
int main()
{
	string a;
	long long temp,ans = 0;
	int i,n,num = 0,j;
	cin>>a;
	n = a.size();
    for(i = n - 1;i >= 0;i--){
		if(a[i] >= '0' && a[i] <= '9'){
		    temp = a[i] - '0';
			for(j = 0;j < num;j++)
                temp *= 16;
            ans += temp;
			num++;
		}
		else if(a[i] >= 'A' && a[i] <= 'F'){
                temp = a[i] - 55;
                for(j = 0;j < num;j++){
                    temp *= 16;
                }
			ans += temp;
			num++;
		}
		else                //如果有小写的话
        if(a[i] >= 'a' && a[i] <= 'f'){
            temp = a[i] - 87;
            for(j = 0;j < num;j++){
                temp *= 16;
            }
            ans += temp;
            num++;
        }
	}
	cout<<ans<<endl;
	return 0;
}

十六进制转化为八进制
十进制转化为16进制
八进制转化为十六进制

//八进制转化为十六进制
#include<stdio.h>
#include<iostream>
#include<stack>
#include<string>
#include<math.h>
using namespace std;
int main()
{
    int ba,bas[88888];
    stack<int>ans;
    int bi[50005];
    cin>>ba;
    int i,j = 0,n,num = 0,count = 0,tmp;
    //八进制转化为二进制
    //提取八进制中的数字
    while(ba){
        tmp = ba % 10;
        //将数字转化为二进制
        while(tmp > 0){
            count++;
            bi[num++] = tmp % 2;
            tmp /= 2;
        }
        while(count < 3){
            count++;
            bi[num++] = 0;
        }
        count = 0;
        ba /= 10;
    }
    for(i = num - 1;i >= 0;i--){
        cout<<bi[i];
    }
    cout<<endl;
    tmp = 0;
    for(i = 0;i < num;i++){//二进制转化为十六进制
        tmp += (pow(2,j) * bi[i]);
        cout<<tmp<< " ";
        j++;
        if(j == 4){
            j = 0;
            ans.push(tmp);
            tmp = 0;
        }
    }
    cout<<endl;
    if(j != 0 && tmp){
        ans.push(tmp);
    }
    while(!ans.empty()){
        tmp = ans.top();
        if(tmp < 10)
            cout<<tmp;
        else
            printf("%c",tmp + 55);
        ans.pop();
    }
    cout<<endl;
    return 0;
}

十进制转化为二进制
十六进制转化为二进制

猜你喜欢

转载自blog.csdn.net/fuzekun/article/details/84027398