C++, N进制转十进制,十进制转N进制

#include<iostream>
using namespace std;

int BaseNToBase10(const char* plnStr, const int iBase);
int Base10ToBaseN(unsigned int uiSrc,int iBse,char *pOutstr);
int main()
{
	char str[200];
	int number = 0;
	int result = 0;
	unsigned int in10=0;
	char str_result[200] = {0};
	unsigned int ibase=0;

	//N进制转十进制
	cout << "请输入n进制数:" << endl;
	cin >> str;
	cout << "请输入当前进制:" << endl;
	cin>>number;

	result = BaseNToBase10(str,number);

	cout << "十进制输出结果:" << result << endl<<endl;

	//10进制转N进制

	cout << "请输入10进制数:" << endl;
	cin >> in10;
	cout << "请输入要转成的进制:" << endl;		
	cin>> ibase;

	Base10ToBaseN(in10, ibase, str_result);

	cout << ibase << "进制输出结果:" << str_result << endl;

	return 0;
}

//N进制转十进制
int BaseNToBase10(const char* plnStr, const int iBase)
{
	int sum = 0;
	int tempn = 0;
	char tempc = plnStr[0];
	
	int len = strlen(plnStr);
	for (int i=0,j = len-1; j >= 0; j--)
	{
		tempc = plnStr[j];
		if (tempc >= '0' && tempc <= '9')
		{
			tempn = tempc - '0';
			//cout << tempn << endl;
		}
		else if (tempc >= 'A' && tempc <= 'Z')
		{
			tempn = 10+tempc - 'A';
			//cout << tempn << endl;
		}
		sum += tempn * pow(iBase , i);
		i++;
		
	}

	return sum;
}

//10进制转N进制
int Base10ToBaseN(unsigned int uiSrc, int iBse, char* pOutstr)
{	
	int i = 0, mod = 0, divide = uiSrc;
	int len = 0;
	char tmpc = '0';
	while (divide / iBse > 0 || (divide > 0 && divide < iBse))
	{
		mod = divide % iBse;
		if (mod >= 10)	//大于10的要转为大写字母
		{
			tmpc = mod - 10 + 'A';
		}
		else
		{
			tmpc = mod + '0';
		}
		pOutstr[i] = tmpc;
		i++;
		divide = divide / iBse;
	}
	//数组转置
	len = strlen(pOutstr);
	for (int j = 0; j < len / 2; j++)
	{
		tmpc = pOutstr[j];
		pOutstr[j] = pOutstr[len - 1 - j];
		pOutstr[len - 1 - j] = tmpc;
	}
	return 0;
}

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值