Saturday , 21 January 2017
Home » C Programs » C Program on Decimal to Hexadecimal Number Conversion

C Program on Decimal to Hexadecimal Number Conversion

Question:

Write a Program in C to input a number in Decimal number system and convert it into its equivalent number in the Hexadecimal number system.

Note: Hexadecimal Number system is a number system which can represent a number in any other number system in terms of digits ranging from 0 to 9 and then A – F only. This number system consists of only sixteen basic digits i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F. Here 10 is represented as A, 11 as B and so on till 15 which is represented as F.

For Example: 47 in the Decimal number system can be represented as 2F in the Hexadecimal number system.

hexadecimal to binary
Figure Illustrating Decimal to Hexadecimal Number System Conversion

Solution:

/*
 * C Program to convert a Decimal number into a Hexadecimal number
 * @author : www.guideforschool.com
 * @Program Type : C Program
 */

#include <stdio.h>
#include <string.h>
int main(void)
{
    int deci,i=0,rem;
    char hex[100]; // array for storing the result
    char dig[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; // array storing digits of hexadecimal system

    printf("\nEnter a decimal number : ");
    scanf("%d",&deci);

    while(deci > 0)
    {
        rem = deci % 16;
        hex[i++] = dig[rem]; // adding the correct hexadecimal digit to the result based on remainder
        deci = deci / 16;
    }

    hex[i] = '\0'; // converting the resultant character array to a string
    strrev(hex); // reversing the string
    printf("\nEquivalent Hexadecimal number = %s",hex);
    return 0;
}

/*
 * Note: If you do not want to use strrev() function,
 * then you can use the following for loop:

   printf("\nEquivalent Hexadecimal number = ");
    for(j=i-1 ;j>=0;j--)
    {
        printf("%c",hex[j]);
    }
 */

Output:

Enter a decimal number : 47
Equivalent Hexadecimal number = 2F

Enter a decimal number : 1243
Equivalent Hexadecimal number = 4DB
[Note: Don’t forget to share these resources and links from our website in your social networking sites with your friends and followers.]

Check Also

C Program to print Pascal Triangle

Simple C Program to print Pascal Triangle without using functions or arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *