开发者

Convert decimal to hexadecimal value

开发者 https://www.devze.com 2023-02-02 10:25 出处:网络
I wrote C code to convert from decimal to hexadecimal, but i compile that one it show only the hexadecimal value of 10 to 15 that mean A to F. Please see my code below.

I wrote C code to convert from decimal to hexadecimal, but i compile that one it show only the hexadecimal value of 10 to 15 that mean A to F. Please see my code below.

main()
{
    int n,r[10],i,d=0,e=1;
    printf("Enter the decimal number\n");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        r[i]=n%16;
        n=n/16;
        d=d+(r[i]*e);
        e=e*10开发者_如何学Go;
    }
    i--;
    for(i=n;i>=0;i--)
    {
        if(r[i]==10)
            printf("A");
        else if(r[i]==11)
            printf("B");
        else if(r[i]==12)
            printf("C");
        else if(r[i]==13)
            printf("D");
        else if(r[i]==14)
            printf("E");
        else if(r[i]==15)
            printf("F");
        else
            printf("hexa decimal value %d\n",d);
    }
}


#include <stdio.h>

int main(void) {
  int n;

  if (scanf("%d", &n) == 1) {
    printf("hexadecimal: %x\n", n);
  }
  return 0;
}


Please format you code.

Perhaps this is a homework, but if you are just interested in the conversion, do it like this.

int decNum;
scanf("%d",&decNum);
print("%x\n",decNum);


Convert Decimal to Hexadecimal in C Language

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
    long int n,n1,rem;
    char *ans="\0",*ch;
    clrscr();
    printf("\nEnter Your Decimal No :: ");
    scanf("%ld",&n);

    n1=n;
    while(n>0)
    {
        rem=n%16;
        ch=NULL;
        sprintf(ch,"%s",((rem==10)?"A":(rem==11)?"B":(rem==12)?"C":(rem==13)?"D":(rem==14)?"E":(rem==15)?"F":"Z"));
        if(strcmp(ch,"Z")==0)
            sprintf(ch,"%ld",rem);
        strcat(ans,ch);
        n=n/16;
    }

    printf("\nYour Decimal No is :: %ld",n1);
    printf("\nConvert into Hexadecimal No is :: %s",strrev(ans));
    printf("\n\n\n\tThank You");
    getch();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消