C程序将八进制转换为十六进制数字系统

时间:2019-09-24 10:13:53

标签: 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);

问题在于程序可以运行,但是在每个十六进制输出中,十六进制数字之前为零,我不知道为什么。

Output

1 个答案:

答案 0 :(得分:1)

我认为是因为

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

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

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

另外,正如Rup所说,在注释中,您使用Oliver的'\ O',而不是'\ 0',

hexadecimal[index]= '\O';
相关问题