十六进制转八进制
思路分析:
39十六进制先转换为4位二进制,3为0011,9为1001,所以39的二进制为
00111001
,又把二进制转化为3位八进制,从右边开始数,001为1,111为7,所以39的八进制为71。
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_SIZE 100000 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n; //十六进制数数量 int i,j,k; // 计数变量 int result; int str_len; scanf("%d",&n); char str[n][MAX_SIZE]; //建立数组,保存16个十六进制数对应的二进制数 char demo[16][4] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"}; memset(str,0,n*MAX_SIZE); //将str初始化为0 for(i=0;i<n;i++){ scanf("%s",str[i]); k=0; str_len = strlen(str[i]); //计数十六进制数长度 int ss = 4*str_len%3; //判断转换后的二进制数数量是否为的倍数,如果不是,需要补0 char temp[4*str_len+3-ss]; memset(temp,0,4*str_len+3-ss); if(ss == 1){ strcat(temp,"00"); k += 2; } if(ss == 2){ strcat(temp,"0"); k +=1; } /* 进行十六进制向二进制数的转换 */ for(j=0;j<str_len;j++) { if(str[i][j]<65){ temp[k++] = demo[str[i][j]-48][0]; temp[k++] = demo[str[i][j]-48][1]; temp[k++] = demo[str[i][j]-48][2]; temp[k++] = demo[str[i][j]-48][3]; } else if(str[i][j]>=65){ temp[k++] = demo[str[i][j]-55][0]; temp[k++] = demo[str[i][j]-55][1]; temp[k++] = demo[str[i][j]-55][2]; temp[k++] = demo[str[i][j]-55][3]; } } temp[k] = 0; //进行输出操作 for(j=0;j<4*str_len;j+=3) { if(j==0){ result=(4*(temp[j]-48) + 2*(temp[j+1]-48) + (temp[j+2]-48)); if( result != 0) printf("%d",result); } else{ result=(4*(temp[j]-48) + 2*(temp[j+1]-48) + (temp[j+2]-48)); printf("%d",result); } } printf("\n"); } return 0; }