思路:每次从输入中获取一个十六进制数存储字符数组,再每次循环将十六进制数每3位化为12位二进制数,再将12位二进制数化为4位八进制数存储结果数组中。
主要利用一个临时数组存储12位二进制一次次转换部分十六进制数。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void function(char ch, char *tempstr, int location);
void function2(char *tempstr, char *result, int location2);
const char chazhao[16][5] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000",
"1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int main(void)
{
int n;
char str[100001]; //字符串
char result2 [10][400001];
char bit[12];
int i, j, k;
int location, location2;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%s", str);
char result[strlen(str)*4]; //足够大的八进制数的空间
location2 = sizeof(result) - 2; //八进制倒数第二个位置
for (j = strlen(str)-1; j >= 0; j-=3) //每三个十六进制变换
{
location = 12;
function(str[j], bit, location-4);
if (j-1 >= 0)
function(str[j-1], bit, location-8);
else {
for (k = 0; k < 4; k++)
bit[location-8+k] = chazhao[0][k];
}
if (j-2 >= 0)
function(str[j-2], bit, location-12);
else {
for (k = 0; k < 4; k++)
bit[location-12+k] = chazhao[0][k];
}
/*for (k = 0; k < 12; k++)
putchar(bit[k]);
putchar('\n');*/
function2(bit, result, location2 - 3);
location2 -= 4;
}
for (k = 0; k <= location2; k++)
result[k] = '0';
result[sizeof(result)-1] = '\0';
k = 0;
int count = 0; //位置
while (result[k] == '0') //以不是0开始
k++;
while (result[k] != '\0')
{
result2[i][count] = result[k];
count++;
k++;
}
result2[i][count] = '\0';
}
for (k = 0; k < n; k++)
puts(result2[k]);
return 0;
}
//将每一位十六进制转换为二进制放入数组
void function(char ch, char *tempstr, int location) //location是拷贝的起始位置
{
int i;
if (isdigit(ch))
ch = ch - '0';
else if (isalpha(ch))
ch = ch - 'A' + 10; //把ch变为相应的值
for (i = 0; i < 4; i++)
{
tempstr[location] = chazhao[ch][i];
location++;
}
}
//将12位二进制放入八进制数组中
void function2(char *tempstr, char *result, int location2) //location2也是起始位置
{
int i;
for (i = 0; i < 12; i+=3)
{
int x2 = tempstr[i] - '0';
int x1 = tempstr[i+1] - '0';
int x0 = tempstr[i+2] - '0';
result[location2] = x2*4 + x1*2 + x0 + '0';
location2++;
}
}