C program to convert Hexadecimal to Decimal number system

Previous Program Next Program

Write a C program to read hexadecimal number from user and convert it to Decimal number system. How to convert from Hexadecimal number system to Decimal number system in C programming. Logic to convert hexadecimal number to decimal number system in C program.

Example

Input

Input hexadecimal: 1A

Output

Decimal number: 26

Required knowledge

Basic C programming, For loop

Hexadecimal number system

Hexadecimal number system is a base 16 number system. It uses 16 symbols to represent all number i.e. 0123456789ABCDEF

Decimal number system

Decimal number system is a base 10 number system. It uses 10 symbols to represent all numbers i.e. 0123456789

Algorithm to convert Hexadecimal to Decimal

Hexadecimal to Decimal conversion
Step by step descriptive logic to convert hexadecimal to decimal number system.
  1. Read any hexadecimal number from user. Store it in some variable hex.
  2. Initialize decimal = 0, digit = length_of_hexadecimal_digit - 1 and i = 0.
  3. Run a loop for each hex digit. Which is the loop structure should look like for(i=0; hex[i]!='\0'; i++).
  4. Inside the loop find the integer value of hex[i]. Store it in some variable say val.
  5. Convert the hex to decimal using decimal = decimal + (val * 16 ^ digit). Where val = hex[i].

Program to convert hexadecimal to decimal

/**
 * C program to convert Hexadecimal to Decimal number system
 */
#include <stdio.h>
#include <math.h>
#include <string.h>

int main()
{
    char hex[17];
    long long decimal, place;
    int i = 0, val, len;

    decimal = 0;
    place = 1;

    /*
     * Input hexadecimal number from user
     */
    printf("Enter any hexadecimal number: ");
    gets(hex);

    /* Find the length of total number of hex digit */
    len = strlen(hex);
    len--;

    /*
     * Iterate over each hex digit
     */
    for(i=0; hex[i]!='\0'; i++)
    {
 
        /*
         * Find the decimal representation of hex[i]
         */
        if(hex[i]>='0' && hex[i]<='9')
        {
            val = hex[i] - 48;
        }
        else if(hex[i]>='a' && hex[i]<='f')
        {
            val = hex[i] - 97 + 10;
        }
        else if(hex[i]>='A' && hex[i]<='F')
        {
            val = hex[i] - 65 + 10;
        }

        decimal += val * pow(16, len);
        len--;
    }

    printf("Hexadecimal number = %s\n", hex);
    printf("Decimal number = %lld", decimal);

    return 0;
}
Output
Enter any hexadecimal number: 1a
Hexadecimal number = 1a
Decimal number = 26

Happy coding ;)

Recommended posts

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment