/* radix_conversion.c
*
* convert a number with a given radix, output a number with a given radix.
* The radix should between 2 and 16.
*
* for example, input:
* 1F 16 2
* output:
* 11111
*
*/
#include <stdio.h>
/*
* printf() used.
*/
#include <string.h>
/*
* atoi() used.
*/
#include <assert.h>
/*
* assert() used.
*/
static int radix_char2int(char ch);
static char radix_int2char(int value);
static char * radix_conversion(char *str_des, char *str_src, int radix_old, int radix_new);
int main(int argc, char* argv[]){
char dn[20];
int r_o, r_n;
assert(4==argc);
r_o=atoi(argv[2]);
r_n=atoi(argv[3]);
radix_conversion(dn,argv[1],r_o,r_n);
printf("%s\n",dn);
return 0;
}
static int radix_char2int(char ch){
if('0'<=ch && ch<='9'){
return ch-'0';
}
else{
return ch-'A'+10;
}
}
static char radix_int2char(int value){
if(0<=value && value<=9){
return value+'0';
}
else{
return value-10+'A';
}
}
static char * radix_conversion(char *str_des, char *str_src, int radix_old, int radix_new){
int sum, sum2;
char * ret, *p;
char ch;
sum=0;
while(*str_src){
sum = sum * radix_old + radix_char2int( *str_src );
str_src++;
}
sum2=sum;
ret = str_des;
if(0 == sum){
*ret = '0';
*(++ret)='\0';
}
else{
while(sum){
*ret = radix_int2char( sum % radix_new );
sum = sum / radix_new;
ret++;
}
*ret = '\0';
p=str_des;
ret--;
while(p<ret){
ch=*p;
*p=*ret;
*ret=ch;
p++;
ret--;
}
}
return str_des;
}
面试的时候要求写个程序:任意进制数(2-16之间的进制)转换
最新推荐文章于 2021-10-02 11:08:49 发布