- C Programming Examples
- C Programming Examples
- C Print Hello World
- C Get Input from User
- C Print Integer
- C Add Two Numbers
- C Add Subtract Multiply Divide
- C Add n Numbers
- C Area Perimeter of Square
- C Area Perimeter of Rectangle
- C Area Circum of Circle
- C Fahrenheit to Celsius
- C Celsius to Fahrenheit
- C Inches to Centimeters
- C Kilogram to Gram
- C Reverse a Number
- C Swap Two Numbers
- C Interchange Numbers
- C Print ASCII Value
- C Print Fibonacci Series
- C Check Palindrome or Not
- C Check Armstrong or Not
- C Find Armstrong Numbers
- C Find nCr and nPr
- C Find Profit Loss
- C Sum of their Square
- C First & Last Digit Sum
- C Sum of All Digit
- C Product of All Digit
- C Print Total Digit in Number
- C Check Perfect Number
- C Find Basic Gross Salary
- C Round Number to Integer
- C Print Series upto n Term
- C Find Factors of Number
- C if-else & Loop Programs
- C Check Even or Odd
- C Check Prime or Not
- C Check Alphabet or Not
- C Check Vowel or Not
- C Check Leap Year or Not
- C Is Reverse Equal Original
- C Make Calculator
- C Add Digits of Number
- Count Positive Negative Zero
- C Largest of Two Numbers
- C Largest of Three Numbers
- C Smallest of Two Numbers
- C Smallest of Three Numbers
- C Find Factorial of Number
- C Find LCM & HCF
- C Find LCM of n Numbers
- C Find HCF of n Numbers
- C Find Arithmetic Mean
- C Find Average, Percentage
- C Find Student Grade
- C Print Table of Number
- C Print Prime Numbers
- C Find Discount Purchase
- C Calculate Parcel Charge
- C Calculate Wage of Labor
- C Print Phone Bill
- C Conversion programs
- C Decimal to Binary
- C Decimal to Octal
- C Decimal to Hexadecimal
- C Binary to Decimal
- C Binary to Octal
- C Binary to Hexadecimal
- C Octal to Decimal
- C Octal to Binary
- C Octal to Hexadecimal
- C Hexadecimal to Decimal
- C Hexadecimal to Binary
- C Hexadecimal to Octal
- C Pattern Programs
- C Pattern Printing Programs
- C Print Diamond Pattern
- C Print Floyd's Triangle
- C Print Pascal's Triangle
- C Array Programs
- C 1D Array Programs
- C Linear Search
- C Binary Search
- C Largest Element in Array
- C Smallest Element in Array
- C Second Largest/Smallest
- C Count Even Odd
- C Array Element at Even
- C Array Element at Odd
- C Print Even Array Elements
- C Print Odd Array Elements
- C Sum/Product of Even/Odd
- C Reverse an Array
- C Insert Element in Array
- C Delete Element from Array
- C Merge Two Arrays
- C Bubble Sort
- C Selection Sort
- C Insertion Sort
- C Print Common Elements
- C 2D Array Programs
- C Add Two Matrices
- C Subtract Two Matrices
- C Transpose a Matrix
- C Multiply Two Matrices
- C Sum All Matrix Elements
- C Largest Element in Matrix
- C Print Row Column Total
- C 3D Array Programs
- C String Programs
- C Print String
- C Find Length of String
- C Compare Two String
- C Copy a String
- C Concatenate String
- C Reverse a String
- C Count Vowels Consonants
- C Replace Vowel in String
- C Delete Vowels from String
- C Delete Word from String
- C Frequency of Character
- C Count Word in String
- C Remove Spaces from String
- C Sort a String
- C Sort String in Alphabetical
- C Sort Words in Ascending
- C Sort Words in Descending
- C Uppercase to Lowercase
- C Lowercase to Uppercase
- C Swap Two Strings
- C Check Anagram or Not
- C Check Palindrome String
- C Print Number in Words
- C Print Successive Character
- C Character without Space
- C File Programs
- C Read a File
- C Write Content to File
- C Read & Display File
- C Copy a File
- C Merge Two Files
- C Reverse File
- C Count All Character in File
- C List Files in Directory
- C Encrypt & Decrypt a File
- C Delete a File
- C Misc Programs
- Generate Random Numbers
- C Print Date Time
- C Print Message with Time
- C Get IP Address
- C Print Smiling face
- C Pass Array to Function
- Add Two Numbers using Pointer
- C Address of Variable
- C Shutdown Computer
- C Programming Tutorial
- C Tutorial
C Program to Convert Hexadecimal to Decimal
In this article, we will learn how to create a program in C that converts any given hexadecimal number entered by the user at run-time into its equivalent decimal value. We have also created a user-defined function that does the same job.
But before going through the program, if you are not aware of
- Hexadecimal Number
- Decimal Number
- Hexadecimal to Decimal Conversion Process
Then follow the steps in the Hexadecimal to Decimal conversion process. Now let's move on to the program.
Hexadecimal to Decimal in C
To convert a hexadecimal number to a decimal number in C programming, you have to ask the user to enter the hexadecimal number to convert it into a decimal number, and then display its equivalent value in decimal as an output. The question is, "Write a program in C that converts a hexadecimal number to a decimal." The answer to this question is:
#include<stdio.h> #include<conio.h> #include<math.h> int main() { int decnum=0, rem, i=0, len=0; char hexnum[20]; printf("Enter any Hexadecimal Number: "); scanf("%s", hexnum); while(hexnum[i]!='\0') { len++; i++; } len--; i=0; while(len>=0) { rem = hexnum[len]; if(rem>=48 && rem<=57) rem = rem-48; else if(rem>=65 && rem<=70) rem = rem-55; else if(rem>=97 && rem<=102) rem = rem-87; else { printf("\nYou've entered an invalid Hexadecimal digit"); getch(); return 0; } decnum = decnum + (rem*pow(16, i)); len--; i++; } printf("\nEquivalent Decimal Value = %d", decnum); getch(); return 0; }
As the above program was written in the Code::Blocks IDE, here is the first snapshot of the sample run:
Now supply any hexadecimal number as input, say A67, and press the ENTER key to see its decimal equivalent, as shown in the second snapshot of the same sample run given below:
Program Explained
- Receive any hexadecimal number as input, say 5A9.
- The entered hexadecimal number gets stored in a character array called hexnum.
- Using a while loop, count the length of the character array hexnum (the given hexadecimal number).
- After determining the length of the given hexadecimal number, decrement the length value (the variable len stores the length value) by one using either len-- or len=len-1. Because indexing in an array starts with 0.
- Initialize i with 0, because we are going to use i as an exponent of 16.
- Now create a while loop that runs from the last index to the first (the 0th index) of the given character array or hexnum.
- Therefore, at first run, the condition of the while loop len>=0 or 2>=0 (as the length of the given hexadecimal number 5A9 is 3, and after decrementing its value by 1, we have a len variable that holds 2 as its value) evaluates to true, therefore program flow goes inside the loop, and hexnum[len] or hexnum[2] or 9 gets initialized to rem.
- As hexnum[2] is a character and rem is an integer type variable, using rem = hexnum[2], the ASCII code of hexnum[2] or 9 gets initialized to rem.
- And as we all know, the ASCII code for 0-9 is 48-57, and the ASCII code for A-F (which corresponds to hex digits 10-15) is 65-70.
- Therefore, we have checked and initialized the corresponding decimal value of a given hexadecimal digit using its ASCII code. That is, if hexnum[2] holds 9, and the ASCII code for 9 is 56, then rem-48, 57-48, or 9 gets initialized to rem.
- After that, decnum + (rem*pow(16, i)) (decnum was initially set to 0 at the beginning of the program) or 0 + (9*pow(16, 0)) or 0 + 9*1 or 9 is assigned to decnum.
- The value of len gets decremented and becomes 1. And the value of i gets incremented and becomes 1.
- Program flow returns to the while loop condition, len>=0 or 1>=0 evaluates to true, and program flow again goes inside the loop.
- Carrying out a similar operation. That is, hexnum[len] or hexnum[1] or A is set to rem. As the ASCII code for A is 65, therefore, rem-55 or 65-55 or 10 (10 represents A in hexadecimal) gets initialized to rem
- Then decnum + (rem*pow(16, i)) or 9 + (10*161) or 9+160 or 169 is set to decnum.
- The value of len gets decremented, and the value of i gets incremented.
- And program flow again goes back to the condition of the loop and does the same operation as told in the above steps.
- After exiting the while loop, we have the decnum variable, which holds the equivalent decimal value of the given hexadecimal number.
- Therefore, print the value of the decnum variable as an output.
What if hexadecimal input contains decimals?
The program given above is only correct when the user supplies any hexadecimal number as input (without any decimal point). However, if he/she enters any hexadecimal number that includes a point (decimal point), you must replace the above program with the one below. The question is, "Write a program in C that converts hexadecimal (including the decimal point) to decimal." The answer to this question is:
#include<stdio.h> #include<conio.h> #include<math.h> int main() { int decnum=0, decnum1=0, rem, i=0, len=0, lenTemp, dotPos=0; float decnum2=0; char hexnum[20]; printf("Enter any Hexadecimal Number: "); scanf("%s", hexnum); while(hexnum[i]!='\0') { if(hexnum[i]=='.') dotPos = i; len++; i++; } len--; i=0; if(dotPos==0) { while(len>=0) { rem = hexnum[len]; if(rem>=48 && rem<=57) rem = rem-48; else if(rem>=65 && rem<=70) rem = rem-55; else if(rem>=97 && rem<=102) rem = rem-87; else { printf("\nYou've entered an invalid Hexadecimal digit"); getch(); return 0; } decnum = decnum + (rem*pow(16, i)); len--; i++; } printf("\nEquivalent Decimal Value = %d", decnum); } else { lenTemp = dotPos-1; while(lenTemp>=0) { rem = hexnum[lenTemp]; if(rem>=48 && rem<=57) rem = rem-48; else if(rem>=65 && rem<=70) rem = rem-55; else if(rem>=97 && rem<=102) rem = rem-87; else { printf("\nYou've entered an invalid Hexadecimal digit"); getch(); return 0; } decnum1 = decnum1 + (rem*pow(16, i)); lenTemp--; i++; } lenTemp = dotPos+1; i=-1; while(lenTemp<=len) { rem = hexnum[lenTemp]; if(rem>=48 && rem<=57) rem = rem-48; else if(rem>=65 && rem<=70) rem = rem-55; else if(rem>=97 && rem<=102) rem = rem-87; else { printf("\nYou've entered an invalid Hexadecimal digit"); getch(); return 0; } decnum2 = decnum2 + (rem*pow(16, i)); lenTemp++; i--; } decnum2 = decnum1+decnum2; printf("\nEquivalent Decimal Value = %0.2f", decnum2); } getch(); return 0; }
Here is a sample run of the above program. This is the final snapshot:
Program Explained
- We used the variable dotPos to determine whether or not a decimal point is present within the given hexadecimal number.
- If present, then we have initialized 1 to the dotPos variable, and we check later whether the dotPos variable holds its previous value (zero) or not.
- If it holds, then we have to apply normal conversion rules as done in the first program given above; otherwise, we have to deal with different rules.
- In hexadecimal number input that contains a decimal point, we have used two-part
- One before and one after the decimal point.
- The before decimal part gets converted into its equivalent decimal value and initialized to decnum1, whereas the after decimal part gets converted into its equivalent decimal value and initialized to decnum2 (a floating point variable).
- Finally, add both variables together and initialize them to a floating-point variable, decnum2.
- and print its value as output.
Hexadecimal to Decimal in C using a User-Defined Function
Now, as shown in the program below, let's create the same purpose program using a user-defined function called HexToDec(). The question is: "Write a program in C that converts hexadecimal to decimal using a user-defined function." The answer to this question is:
#include<stdio.h> #include<conio.h> #include<math.h> int HexToDecY(char hex[]); float HexToDecN(char hex[]); static int i, len, dotPos; int main() { int decnumInt; float decnumFlt; char hexnum[20]; printf("Enter any Hexadecimal Number: "); scanf("%s", hexnum); while(hexnum[i]!='\0') { if(hexnum[i]=='.') dotPos = i; len++; i++; } len--; i=0; if(dotPos==0) { decnumInt = HexToDecY(hexnum); if(decnumInt!=0) printf("\nEquivalent Decimal Value = %d", decnumInt); } else { decnumFlt = HexToDecN(hexnum); if(decnumFlt!=0) printf("\nEquivalent Decimal Value = %0.2f", decnumFlt); } getch(); return 0; } int HexToDecY(char hex[20]) { int dec=0, rem; while(len>=0) { rem = hex[len]; if(rem>=48 && rem<=57) rem = rem-48; else if(rem>=65 && rem<=70) rem = rem-55; else if(rem>=97 && rem<=102) rem = rem-87; else { printf("\nYou've entered an invalid Hexadecimal digit"); return 0; } dec = dec + (rem*pow(16, i)); len--; i++; } return dec; } float HexToDecN(char hex[20]) { int dec1=0, rem, lenTemp; float dec2=0; lenTemp = dotPos-1; while(lenTemp>=0) { rem = hex[lenTemp]; if(rem>=48 && rem<=57) rem = rem-48; else if(rem>=65 && rem<=70) rem = rem-55; else if(rem>=97 && rem<=102) rem = rem-87; else { printf("\nYou've entered an invalid Hexadecimal digit"); return 0; } dec1 = dec1 + (rem*pow(16, i)); lenTemp--; i++; } lenTemp = dotPos+1; i=-1; while(lenTemp<=len) { rem = hex[lenTemp]; if(rem>=48 && rem<=57) rem = rem-48; else if(rem>=65 && rem<=70) rem = rem-55; else if(rem>=97 && rem<=102) rem = rem-87; else { printf("\nYou've entered an invalid Hexadecimal digit"); return 0; } dec2 = dec2 + (rem*pow(16, i)); lenTemp++; i--; } dec2 = dec1+dec2; return dec2; }
Here is the final snapshot of the above program's sample run.
Program Explained
- We have initialized the variables i, len, and dotPos as static and global variables.
- As a result, all three variables retain their previous values and are known throughout the program.
- We have not initialized 0 to all three static variables because static variables automatically hold 0 as their initial value.
- We have used two functions named HexToDecY() and HexToDecN().
- The function HexToDecY() deals with hexadecimal input without a decimal point, and the function HexToDecN() deals with hexadecimal input with a decimal point.
- We have supplied 65A7.98 as a hexadecimal number input.
- It contains a decimal point, therefore the HexToDecN() function gets called and executed.
- And finally, it returns dec2 to the main() function, which contains the decimal equivalent of the given hexadecimal number 65A7.98.
- In the main() function, the value of dec2 gets initialized to the decnumFlt variable, and the value of it gets printed as output.
Now let's take another sample run; this time we have supplied a hexadecimal number without any decimal point, as shown in the sample run given below. Here is another final snapshot of the sample run:
The same program in different languages
« Previous Program Next Program »