2-36进制转换 C语言

#include<stdio.h>
#include<conio.h>
#include<string.h>

/*
N进制转换为M进制的数 
*/

/*
将N进制的数转换成十进制的数 
@n  进制数
@nHex  n进制数的字符数组

return 生成的long型十进制数 
*/
int converNHexNumberToDecimalNumber(int n, char nHex[]) {
	int i;
	long num = 0;
	char c;
	for(i = 0; i < strlen(nHex); i++) {
		c = nHex[i];
		if(c < 58 )
			num = num * n + c - '0';
		else 
			num = num * n + c - 'A' + 10;
	}
	return num;
}

/*
将十进制的数转换成m进制的数 
@m	进制数 
@num	十进制数 
@mHex	m进制数组 

return top栈顶标识 
*/ 
int converDecimalNumberToMHexNumber(int m, long num, char mHex[]) {
	int top = 0, intHex;
	char chHex;
	if(num / m > 0) {
		do {
			intHex = num % m;
			if(intHex < 10) 
				mHex[top++] = intHex + '0';
			 else 
				mHex[top++] = 'A' + intHex - 10;  
			num /= m;
		} while(num / m > 0);
	} 
	if(num < 10)
		mHex[top] = num + '0';
	else
		mHex[top] = num + 'A';
	return top;
}

/*
将字符数组中所有的小写字母转换成大写字母,
如果存在不是大小写字母与数字的返回 0
否则返回1 
@nHex 字符数组
*/ 
int toUpperCase(char nHex[]) {
	int i;
	for(i = 0; i < strlen(nHex); i++) {
		if( (nHex[i] >= '0' && nHex[i] <= '9') || (nHex[i] >= 'A' && nHex[i] <= 'Z') || (nHex[i] >= 'a' && nHex[i] <= 'z')) {
			if(nHex[i] >= 'a' && nHex[i] <= 'z') 
				nHex[i] -= 32; 
		} else {
			return 0;
		}	
	}
	return 1;
}

int main(void)
{
	int n, m, top;
	long num;
	char mHex[20];
	char nHex[20];
	char action;
	printf("It's the program which conver nHex number to mHex number!\n");
	printf("(2 <= m(n) <= 36)\n");
	printf("\n\n");
	do {
		printf("Please input the n and m for each:\n");
		scanf("%d%d", &n, &m);
		getchar();
		if(n == m) {
			printf("Hex is the same! Not need to convert!\n");
			printf("Press Any key to exit!\n");
			getch();
			system("cls");
			continue;
		} else if(n < 2 || n > 36 || m < 2 || m > 36) {
			printf("Out of the Hex number range!\n");
			printf("Press Any key to exit!\n");
			getch();
			system("cls");
			continue;
		}
		printf("Please input the %d Hex number:\n", n);
		gets(nHex);
		if(!toUpperCase(nHex)) {
			printf("Invalid Data!\n");
			printf("Press Any Key to exit!\n");
			system("cls");
			continue;
		}	
		printf("The convered %d Hex number is :\n", m);
		num = converNHexNumberToDecimalNumber(n, nHex);
		top = converDecimalNumberToMHexNumber(m, num, mHex);
		while(top >= 0) 
			printf("%c", mHex[top--]);
		printf("\n");
		do {
			printf("Continue?(Y/N)");	
			action = getch();	
			printf("\n");
		} while(action != 'y' && action != 'Y' && action != 'N' && action != 'n');
		
		printf("\n");
		
	} while(action == 'Y' || action == 'y');
	
	printf("Byb-Byb!\n");
	printf("Press Any Key to exit!\n");
	getch();
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值