建议掌握前两种,考试无论怎么出题都能转换
1. r进制转换成十进制
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define maxSize 100
//r进制转换成10进制
int BaseToTen(const char* s,int base)
{
int i = 0;
int num = 0;
int tmp;
while (s[i] != '\0')
{
if (isalpha(s[i]))
{
tmp = s[i] - 'A' + 10;
}
else
{
tmp = s[i] - '0';
}
num = num*base + tmp;
i++;
}
return num;
}
int main()
{
int x = BaseToTen("A12",16);
printf("%d", x);
return 0;
}
2.十进制转r进制
3. 二进制转八进制或十六进制
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define maxSize 100
void Conversion(char a[], char b[], int low, int high, int r);
//2进制转换成8/16进制,a数组长度必须是3或者4的倍数
void BinaryToBase(char a[], char b[], int base)
{
int r = 0, len;
//先判断是几进制,如何是8进制则为3,如果是16进制则为4
while (base != 1)
{
r++;
base /= 2;
}
len = strlen(a);
Conversion(a, b, 0, len - 1, r);
}
void Conversion(char a[], char b[], int low, int high,int r)
{
if (low + r - 1 <= high)
{
int i,sum;
char ch;
//每r个数为一组计算和
sum = 0;
for (i = low; i <= low + r - 1; ++i)
{
sum = sum * 2 + a[i] - '0';
}
//写入b中
if (sum > 9)
{
ch = sum - 10 + 'A';
}
else
{
ch = sum + '0';
}
*b = ch;
*(b+1) = '\0';
Conversion(a, b + 1, low + r, high, r);
}
}
int main()
{
char a[100] = "001101101110", b[100];
BinaryToBase(a, b,16);
puts(b);
return 0;
}
4.十六进制或八进制转二进制
制作对应二进制与八和十六进制转换表,然后利用对照表进行字符串之间的连接操作