Chuyển số từ cơ số bất kỳ sang thập phân và ngược lại.
Chuyển sang thập phân
#include <stdio.h>
#include <string.h>
int val(char c){
if (c >= '0' && c <= '9') return c - '0';
else return c - 'A' + 10;
}
int convert_decimal(char *str, int base){
int len = strlen(str);
int power = 1, num = 0;
for (int i = len-1; i >= 0; i--){
if (val(str[i]) >= base) { printf("Invalid Number"); return -1; }
num += val(str[i]) * power;
power *= base;
}
return num;
}
int main(){
char str[] = "11A"; int base = 16;
printf("Decimal equivalent of %s in base %d is %d\n", str, base, convert_decimal(str, base));
return 0;
}
Kết quả
Decimal equivalent of 11A in base 16 is 282
Chuyển từ thập phân sang cơ số b
#include <stdio.h>
#include <string.h>
char reVal(int num){
if (num >= 0 && num <= 9) return (char)(num + '0');
else return (char)(num - 10 + 'A');
}
void reverse_string(char *str){
int len = strlen(str);
for (int i = 0; i < len/2; i++){
char temp = str[i]; str[i] = str[len-i-1]; str[len-i-1] = temp;
}
}
char* convert_base(char res[], int base, int inputNum){
int index = 0;
while (inputNum > 0){
res[index++] = reVal(inputNum % base);
inputNum /= base;
}
res[index] = '\0';
reverse_string(res);
return res;
}
int main(){
int inputNum = 282, base = 16;
char res[100];
printf("Equivalent of %d in base %d is %s\n", inputNum, base, convert_base(res, base, inputNum));
return 0;
}
Kết quả
Equivalent of 282 in base 16 is 11A