首页 > 解决方案 > 八进制转十六进制的C程序

问题描述

我已经编写了下面的代码来将八进制转换为十六进制数:

int main()
{
int octal[100]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int binary[100]={0, 1, 10, 11, 100, 101, 110, 111, 1000,1001, 1010, 1011, 1100, 1101, 1110, 1111};
int Hinary[100]={0, 1, 10, 11, 100, 101, 110, 111, 1000,1001, 1010, 1011, 1100, 1101, 1110, 1111};
long long tempoctal,last1,binar,hocatl,place=1;
long long i,tempbinary,last2,index;
char hexadecimal[100];
index=0;
binar=0;

printf("enter an octal number:  ");
scanf("%lld",&hocatl);

tempoctal=hocatl;

while(tempoctal != 0){

    last1=tempoctal%10;

    binar=(binary[last1] * place) + binar;


    place *= 1000;

    tempoctal /=10;

}

tempbinary=binar;
printf("this is the number: %lld",tempbinary);

while(tempbinary != 0){

    last2=tempbinary%10000;
      for(i=0 ; i<16 ; i++){

       if(Hinary[i] == last2){
       if(i<10){  hexadecimal[index]= i + '0';  }
       else{  hexadecimal[index]= (i-10) + 'A' ;  }
       }

      }
    index++;
    tempbinary /=10000;


}
hexadecimal[index]= '\O';
strrev(hexadecimal);
printf("\nthis is the hex: %s",hexadecimal);

问题是程序可以工作,但是在每个十六进制输出中,十六进制数字前都有一个零,我不知道为什么。

输出

标签: c

解决方案


我认为它的出现是因为

if(i<10){  hexadecimal[index]= i + '0';  }

要解决您的零问题,您可以在打印之前使用它:

if (hexadecimal[0] == '0')
{
    hexadecimal++;
}

此外,正如 Rup 所说,在评论中,您在这里使用来自 Oliver 的 '\O',而不是 '\0':

hexadecimal[index]= '\O';

推荐阅读