㈠ 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]='