Blue Bridge Cup C language hexadecimal to octal

Hexadecimal to Octal

insert image description here

Thought analysis:

39 hexadecimal is first converted to 4-bit binary, 3 is 0011, 9 is 1001, so the binary of 39 is 00111001, and the binary is converted to 3-bit octal, counting from the right, 001 is 1, 111 is 7, so 39 The octal is 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;
}

Guess you like

Origin blog.csdn.net/A6_107/article/details/122986203