十六进制转八进制
作者:互联网
#include<stdio.h>
#include<string.h>
int main()
{
int n,i,j,k,a,cur,ok,m,l;
char s[10][100001];
char d16[16][5]={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
char out[140000]={};
char z[13]={};
scanf("%d",&n);
for(j=0;j<n;j++)
scanf("%s",s[j]);
for(j=0;j<n;j++)
{
k=0;ok=1;m=0; /*初始化标记数据*/
l=strlen(s[j]); /* 初始化标记数据*/
a=3-l%3; /*初始化标记数据*/ //求出要将这个十六进制数补足为3的倍数需要补上多少个0
if(a==3) ok=0; /*十六进制数长度刚好为3的倍数时转二进制不需补0,ok标记其是否为3的倍数0是1不是*/
for(i=0;i<l;i++) /*逐位读取十六进制数进行转换*/
{
if(65<=s[j][i])
s[j][i]-=7; //这里不理解请查阅ASCII代码表
if(ok) /*十六进制数位数不足转二进制时补0占位*/
if(a==1){ //若需补一个十六进制的0,相当于补上四个二进制的0即0000,下面补两位也一样
strcat(z,"0000");k=k+4;ok=0;
}else if(a==2){
strcat(z,"00000000");k=k+8;ok=0;
}
z[k++]=d16[s[j][i]-48][0]; /*一位十六进制转四位二进制*/
z[k++]=d16[s[j][i]-48][1];
z[k++]=d16[s[j][i]-48][2];
z[k++]=d16[s[j][i]-48][3];
if(k==12) /*每转三位十六进制数将其转为四位八进制数*/
{
for(cur=0;cur<12;m++)
out[m]=((z[cur++]-48)*4+(z[cur++]-48)*2+(z[cur++]-48)*1)+48;
z[0]='\0';k=0; /*z[0]='\0'初始化字符串结束符位置避免溢出*/
}
}
for(;k<3;k++) /*输出时忽略前导0*/
if(out[k]!=48) break; //48是字符‘0’的ASCII值
for(;k<m;k++)
printf("%c",out[k]);
putchar('\n');
}
return 0;
}
标签:十六进制,0110,include,int,char,八进制 来源: https://www.cnblogs.com/onesun/p/15823441.html