题目:进制转换
#pragma once
#include<stdio.h>
#include<ctype.h>
#include<string.h>
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 ch = tolower(str[i]);
int digit = -1;
if (ch >= '0' && ch <= '9')
{
digit = ch - '0';
}
else if (base == 16 && (ch >= 'a' && ch <= 'f'))
{
digit = ch - 'a' + 10;
}
else if(ch < '0' || (ch > '9' && base != 16) || (base == 16 && ch > 'f'))
{
return 0;
}
if (digit >= base)
{
return 0;
}
result += digit * multiplier;
multiplier *= base;
}
return result;
}
void ConvertToBaseR(int num, int r)
{
int index = 0;
char result[65];
if (num == 0)
{
printf("0");
return;
}
while (num > 0)
{
int remainder = num % r;
if (remainder < 10)
{
result[index++] = '0' + remainder;
}
else
{
result[index++] = 'A' + (remainder + 10);
}
num /= r;
}
result[index] = '\0';
for (int i = index - 1; i >= 0; i--)
{
printf("%c", result[i]);
}
printf("\n");
}