-->
Showing posts with label hexadecimal to decimal conversion. Show all posts
Showing posts with label hexadecimal to decimal conversion. Show all posts

program to convert hexadecimal number into decimal .

//program to convert hexadecimal number into decimal .
#include <stdio.h>
#include <math.h>
#include <string.h>
void main()
{
    char hex_number[20];
    long long deci=0, place=1;
    int i = 0, val, len;
    /*
     * entering hexadecimal number from user
     */
    printf("Enter any hexadecimal number: \n");
    gets(hex_number);
     
    /* get/find the length of total number of hex digit (inputted as string)*/
    len = strlen(hex_number);
     len--;//it decreases the value of total length by 1 because we need one less value
       //  for multiplication. and array stores value from location 0
    /*
     * Converts the hexadecimal number to decimal number
     * using algorithm/formula for conversion
           deci = deci + (hex_number[i] * 16 ^ power)
     */
    for(i=0; hex_number[i]!='\0'; i++)
    {
        /*
         * Finds the decimal each equivalent hexadecimal digit
         following logic takes one character,converts into value as val  and then 
          goes for calculation.
         */
        switch(hex_number[i])
        {
            case '0':
                val = 0;
                break;
            case '1':
                val = 1;
                break;
            case '2':
                val = 2;
                break;
            case '3':
                val = 3;
                break;
            case '4':
                val = 4;
                break;
            case '5':
                val = 5;
                break;
            case '6':
                val = 6;
                break;
            case '7':
                val = 7;
                break;
            case '8':
                val = 8;
                break;
            case '9':
                val = 9;
                break;
            case 'a':
            case 'A':
                val = 10;
                break;
            case 'b':
            case 'B':
                val = 11;
                break;
            case 'c':
            case 'C':
                val = 12;
                break;
            case 'd':
            case 'D':
                val = 13;
                break;
            case 'e':
            case 'E':
                val = 14;
                break;
            case 'f':
            case 'F':
                val = 15;
                break;
        }
        deci += val * pow(16, len);
        len--;
    }
    printf("\Hexadecimal number = %s\n", hex_number);
    printf("equivalent Decimal number = %ld", deci);  
}


logics in mind:

-> hexadecimal number contains characters A,B,C,D,E, and F
-> we have to check and extract all characters one by one then we go for multiplication with increasing or
     decreasing power
->we have to go for sum
->display that sum