题目:进制转换合集。任意r进制与十进制之间的转换
c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
long stringToDecimal(const char* str, int base);
void convertToBaseR(int num, int r);
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));
int num, r;
printf("请输入十进制的整数: ");
scanf_s("%d", &num);
printf("请输入要转化的进制数: ");
scanf_s("%d", &r);
convertToBaseR(num, r);
return 0;
}
/// <summary>
/// 将字符串str转为十进制
/// </summary>
/// <param name="str">字符串</param>
/// <param name="base">基数2, 8, 16等</param>
/// <returns></returns>
long stringToDecimal(const char* str, int base) {
long result = 0;
int multiplier = 1;
int length = strlen(str);
//从字符串末尾开始解析
for (int i = length - 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;//更新下一次计算的基数
}
}
/// <summary>
/// 将十进制数转换成任意的r进制数
/// </summary>
/// <param name="num">数字</param>
/// <param name="r">要转换的目标进制数</param>
void convertToBaseR(int num, int r) {
int index = 0;
char result[65];//假设转换后的数不超过64位
//处理num = 0的情况
if (num == 0) {
printf("0\n");
return;
}
while (num > 0)
{
int remainder = num % r;
if (remainder < 10) {
result[index++] = '0' + remainder;//余数小于10的,将其转换成0~9之间的字符
}
else
{
result[index++] = 'A' + (remainder - 10);//余数大于10的,将其转换成'A' ~ 'Z' 字符
}
num = num / r; //更新下一次参与计算的数字
}
result[index] = '\0'; //在字符串末尾添加结束符
//因为结果是从低位到高位存储的,所以需要反向打印
for (int i = index; i >= 0; i--)
{
printf("%c", result[i]);
}
printf("\n");
}