This blog is under construction

Thursday 4 July 2013

C Program to convert hexadecimal to decimal

How to convert Hexadecimal Value to Decimal Value?
Hexadecimal value 0x5A1
(5 X 16 ^ 2) + (10 X 16 ^ 1) + (1 X 16 ^ 0) = (5 X 256) + (10 X 16) + 1 = 1441
Find the hexadecimal value for individual digits.  Multiply each digit with their corresponding power of 16 and calculate the sum of all.

Write a C program to convert hexadecimal to decimal value.


  #include <stdio.h>
  #include <math.h>
  #include <string.h>

  int main () {
        char input[10], ch;
        int value = 0, power = 0, i = 0, j = 0;

        /* get the hexadecimal value from the user */
        printf("Enter your hexadecimal value:");
        fgets(input, 10, stdin);
        input[strlen(input) - 1] = '\0';

        /* convert hexadecimal value to decimal */
        for (i = strlen(input); i > 0; i--) {
                ch = input[j++];
                power = pow(16, i - 1);
                if (ch >='0'&& ch <= '9') {
                        /*
                         * input character is any value from 0 to 9
                         */
                        value = value + (ch - '0') * power;
                } else if (ch >= 'a' && ch <= 'f') {
                        /*
                         * input character is any value from a to f
                         * a is 10, b is 11... F is 15 - conversion
                         */
                        value = value + (ch - 'a' + 10) * power;
                } else if (ch >= 'A' && ch <= 'F') {
                        /*
                         * input character is any value from A to F
                         * A is 10, B is 11.. F is 15 - conversion
                         */
                        value = value + (ch - 'A' + 10) * power;
                } else {
                        /*
                         * valid hexadecimal values 0-9, a-f, A-F
                         * if input doesn't belong to any of the
                         * above values, then its a wrong input
                         */
                        printf("Wrong Input!!!\n");
                        return (-1);
                }
        }
        printf("Equivalent Decimal Value: %d\n", value);
        return 0;
  }


Note:
gcc hex2dec.c -lm => link math library since we have used pow() function.

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your hexadecimal value:5a1
  Equivalent Decimal Value: 1441



No comments:

Post a Comment