背景
正做到[PAT B1022]进制转换的问题,在完成题目的基础上,由于懒惰这一进步动力的驱使,我干脆有了把进制转换写成函数的想法……
由于我们日常使用的都是十进制数,而计算机使用二进制(进而有了八进制和十六进制,当然,其原理一样),在此不妨以十进制为接口,充当目的进制和源进制作为中转实现任意进制的互转。
实际用到的进制最高为16,所以下面的代码中限制进制为2到16(1进制显然没有意义),各数位上的代号有0、1、2、3、4、5、6、7、8、9、A、B、C、D、E、F。当然,如果将键盘上的数字与全部字母结合起来,可以达到36进制(忽略大小写的区别),或62进制(不忽略大小写,但这么大的进制数有什么意义……),故,仍将进制基数大小限制在2到16范围内(而其中常用的其实也就只有上面说到的十进制、二进制和十六进制)。
十进制转N进制
代码
#include <cstdio>
#include <cstring>
using namespace std;
char* dec2nbase(int decint, int base, char* coes) {
if(decint>=0) {
if(1<base && base<=16){
int i = 0, temp[33] = {0};
do {
temp[i++] += decint%base;
decint /= base;
} while(decint != 0);
for(int j = 0; j <= i-1; j++) {
if(temp[i-1-j] < 10)
coes[j] = '0'+temp[i-1-j];
else
coes[j] = 'A'+temp[i-1-j]-10;
}
return coes;
}
else
return NULL;
} else
return NULL;
}
int main() {
printf("Input: decimal integer D and base N(1<N<=16)\n");
int D, N;
char coes[33];
while(scanf("%d%d", &D,&N) != EOF) {
memset(coes, 0, sizeof(coes)); //need "string.h"
char* nbasenum = dec2nbase(D, N, coes);
printf("Convert to %d-base integer: %s\n", N, nbasenum);
}
return 0;
}
实验
N进制转十进制
代码
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int nbase2dec(int base, char* coes) {
if(1<base && base<=16){
int coe, res = 0;
int len = strlen(coes); //need "string.h"
for(int i = len-1; i >= 0; i--) { //从最低位算起
if('0'<=coes[i] && coes[i]<='9')
coe = coes[i]-'0';
else if('A'<=coes[i] && coes[i]<='F')
coe = coes[i]-'A' + 10;
else {
printf("Number illegal!\n");
return -1;
}
if(coe < base)
res += coe * pow(base, len-1-i); //need "math.h"
else
return -1;
}
return res;
} else
return -1;
}
int main() {
printf("Input: base N(0<N<=16) and positive N-based integer C\n");
char coes[32];
int base, decnum;
while(scanf("%d%s", &base, coes) != EOF) {
decnum = nbase2dec(base, coes);
printf("Convert to decimal integer: %d\n", decnum);
}
return 0;
}