VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-for-hexadecimal-to-decimal/

⇱ Program for Hexadecimal to Decimal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program for Hexadecimal to Decimal

Last Updated : 3 Apr, 2025

Given a hexadecimal number as input, we need to write a program to convert the given hexadecimal number into an equivalent decimal number.

Examples:

Input : 67
Output: 103

Input : 512
Output: 1298

Input : 123
Output: 291

Hexadecimal Number

We know that hexadecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all numbers. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15). 

The idea is to extract the digits of a given hexadecimal number starting from the rightmost digit and keep a variable dec_value. At the time of extracting digits from the hexadecimal number, multiply the digit with the proper base (Power of 16) and add it to the variable dec_value. In the end, the variable dec_value will store the required decimal number.

For Example: If the hexadecimal number is 1A. 
dec_value = 1*(161) + 10*(160) = 26

Decimal Number

The number which can be represented using the numbers in the range of (0-9) are termed as decimal number which has the base 10 to it.

For example, The number 123 is a decimal number where:

  • 1 represents 100 (10²),
  • 2 represents 20 (10¹),
  • 3 represents 3 (10⁰).

Thus, 123 = 1×100 + 2×10 + 3×1.

The below diagram explains how to convert a hexadecimal number (1AB) to an equivalent decimal value:  

👁 Image


Below is the implementation of the above idea. 


Output
26

Time Complexity: O(N), where N is the number of digits in the given hexadecimal number.

Space Complexity: O(1).

Using predefined function


Output
26

Time complexity: O(1) - the conversion of hexadecimal to decimal is done in constant time using the stoi function.
Auxiliary Space: O(1) - the only space used is for the string n and the returned integer value, which are constant in size regardless of the input value.

Comment
Article Tags:
Article Tags: