题目:写一个函数,输入一个十六进制/八进制数/二进制数,输出对应的十进制数
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
long stringToDecimal(const char* str, int base);
int main() {
char hexStr[] = "1A3F";
char octStr[] = "123";
char binStr[] = "101010";
printf("十六进制转换成十进制:%ld\n", stringToDecimal(hexStr, 16));
printf("八进制转换成十进制:%ld\n", stringToDecimal(octStr, 8));
printf("二进制转换成十进制:%ld\n", stringToDecimal(binStr, 2));
return 0;
}
long stringToDecimal(const char* str, int base) {
long result = 0;
int multiplier = 1;
int len = strlen(str);
for (int i = len - 1; i >= 0; i--)
{
char c = tolower(str[i]);
int digit = -1;
if ( c >= '0' && c <= '9') {
digit = c - '0';
}
else if (base == 16 && (c >= 'a' && c <= 'f')) {
digit = c - 'a' + 10;
}
else if (c < '0' || (c > '9' && base != 16) || (base == 16 && c > 'f')) {
return 0;
}
if (digit >= base) {
return 0;
}
result += digit * multiplier;
multiplier *= base;
}
return result;
}