㈠ c语言如何把十六进制转换成八进制
此题涉及到大数据处理(输入的16进制数最大可能到100000位),所以不能用常规的除8模8方法做,思路:
先将十六进制转为二进制表示
再将二进制转换为八进制表示,然后输出
具体程序实现如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*将十六进制字符转换为数值*/
intget_value(constcharc)
{
if(c>='0'&&c<='9')
returnc-'0';
else
returnc-'A'+10;
}
intmain()
{
char*input,*output,*output2,*ptr;
intn,i,j,tmp,len;
scanf("%d ",&n);
input=(char*)malloc(100000+1);/*储存输入的十六进制数*/
output=(char*)malloc(100000*4+4);/*储存过度用的二进制数*/
output2=(char*)malloc(100000*3+3);/*储存最终结果八进制数*/
while(n--)
{
gets(input);
len=strlen(input);
ptr=input;
j=0;
/*首先将十六进制转换为二进制,1位十六进制数对应4位二进制数*/
while(*ptr)
{
tmp=get_value(*ptr);
output[j++]=((tmp>>3)&0x1);/*bit3*/
output[j++]=((tmp>>2)&0x1);/*bit2*/
output[j++]=((tmp>>1)&0x1);/*bit1*/
output[j++]=((tmp>>0)&0x1);/*bit0*/
ptr++;
}
/*将二进制转换为八进制,3位二进制数对应1位八进制数,从低位开始转*/
/*j为二进制数组下标,每个循环减3*/
/*i为八进制数组下标,每个循环减1*/
j=len*4-1;
i=(len*4+2)/3-1;
output2[i+1]='