简体   繁体   English

C 程序将八进制转换为十六进制

[英]C program to convert Octal to Hexadecimal number system

i have written the code below to covert octal to hexadecimal number:我已经编写了下面的代码来将八进制转换为十六进制数:

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);

the problem is that the program work but in every hex output there is a zero before the hex number and i don't know why.问题是程序可以工作,但是在每个十六进制 output 中,十六进制数字前都有一个零,我不知道为什么。

输出

I think it appears because of我认为它的出现是因为

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

To fix your zero problem, you can use this before printing:要解决您的零问题,您可以在打印之前使用它:

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

Also, as Rup says, in the comments, you use '\O', from Oliver, not '\0', here:此外,正如 Rup 所说,在评论中,您在这里使用来自 Oliver 的 '\O',而不是 '\0':

hexadecimal[index]= '\O';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM