1、任意进制转十进制
long long anyToDecimal(char *str, int base) {
long long result = 0;
for (int i = 0; str[i]; i++) {
int digit = isdigit(str[i]) ? str[i] - '0' : toupper(str[i]) - 'A' + 10;
result = result * base + digit;
}
return result;
}
代码中的toupper是将小写字母转为大写字母。result = result * base + digit代码是最核心的。
2、十进制(非负整数)转任意进制
void decimalToAny(long long num, int base, char *output) {
char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char temp[100];
int index = 0;
if (num == 0) {
output[0] = '0';
output[1] = '\0';
return;
}
while (num > 0) {
temp[index++] = digits[num % base];
num /= base;
}
for (int i = 0; i < index; i++) {
output[i] = temp[index - 1 - i];
}
output[index] = '\0';
}
先不断整除取余填充temp数组,最后别忘记将temp数组反转。
3、任意进制转任意进制
void anyToAny(char *input, int fromBase, int toBase, char *output) {
long long decimal = anyToDecimal(input, fromBase);
decimalToAny(decimal, toBase, output);
}
采用中转法。