#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-36进制转换 C语言
最新推荐文章于 2022-05-10 14:09:46 发布