Loop Assignment 18 — Convert a Hexadecimal String to Decimal Using a For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Convert a Hexadecimal String to Decimal Using a For Loop — Base 16 to Base 10 Conversion

📑 On this page:
  • How Hexadecimal to Decimal Conversion Works
  • The Three Steps of Conversion
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to convert a hexadecimal string into a decimal number
  • How hexadecimal digits 0-9 and A-F are represented
  • How to process a string from right to left using a for loop
  • How to calculate powers of 16 without using pow()
  • How to validate invalid hexadecimal characters
  • Why hexadecimal is a base-16 number system

How Hexadecimal to Decimal Conversion Works

Hexadecimal is a base-16 number system. It uses 16 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. The letters A to F represent decimal values 10 to 15.

To convert a hexadecimal number to decimal, each digit is multiplied by 16 raised to the power of its position from the right. The rightmost digit is multiplied by 160, the next digit by 161, the next by 162, and so on.

For example, hexadecimal 1A is converted as: \(1 \times 16^1 + 10 \times 16^0 = 16 + 10 = 26\). Therefore, hexadecimal 1A equals decimal 26.

💡 In one line: Convert every hexadecimal digit to its decimal value, multiply it by the correct power of 16, and add all results.

Diagram showing conversion of a hexadecimal string to decimal using powers of 16 in C

The Three Steps of Conversion

Step Operation Effect
1. Convert the digit0-9, A-F, or a-fEach hexadecimal character becomes a decimal value from 0 to 15
2. Apply place valuevalue * baseThe digit is multiplied by the current power of 16
3. Add to the resultdecimal += value * base;The converted value is added to the final decimal answer

The program processes the hexadecimal string from the last character to the first character. The variable base starts at 1 and is multiplied by 16 after every iteration.

Both uppercase and lowercase hexadecimal letters are accepted. For example, 1A, 1a, and 1A all represent the same decimal value 26.

Complete C Program

Program: convert a hexadecimal string to decimal using a for loop

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

#define MAX 100

int main(void) {
    char hex[MAX];
    int length, i, value;
    long decimal = 0;
    long base = 1;
    int valid = 1;

    printf("Enter a hexadecimal number: ");
    if (scanf("%99s", hex) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    length = strlen(hex);

    for (i = length - 1; i >= 0; i--) {
        if (hex[i] >= '0' && hex[i] <= '9') {
            value = hex[i] - '0';
        }
        else if (hex[i] >= 'A' && hex[i] <= 'F') {
            value = hex[i] - 'A' + 10;
        }
        else if (hex[i] >= 'a' && hex[i] <= 'f') {
            value = hex[i] - 'a' + 10;
        }
        else {
            printf("\nInvalid hexadecimal number.\n");
            valid = 0;
            break;
        }

        decimal = decimal + value * base;
        base = base * 16;
    }

    if (valid == 1) {
        printf("\nDecimal equivalent: %ld\n", decimal);
    }

    return 0;
}
                                    

Program Output

Enter a hexadecimal number: 1A

Decimal equivalent: 26
                                

A second run, with lowercase hexadecimal letters:

Enter a hexadecimal number: ff

Decimal equivalent: 255
                                

In the first run, hexadecimal 1A is converted to decimal 26. In the second run, hexadecimal ff is converted to decimal 255 because F represents 15, and \(15 \times 16 + 15 = 255\).

Step-by-Step Explanation

Let us understand how the program converts hexadecimal 1A into decimal.

1. Initial values

The hexadecimal string is "1A". Its length is 2. The variables are initialized as decimal = 0 and base = 1.

2. Processing the last character

The last character is 'A'. Since it is between 'A' and 'F', its value is calculated as 'A' - 'A' + 10, which is 10. Then decimal = 0 + 10 * 1, so decimal becomes 10. The base becomes 16.

3. Processing the first character

The next character is '1'. Since it is between '0' and '9', its value is calculated as '1' - '0', which is 1. Then decimal = 10 + 1 * 16, so decimal becomes 26.

4. Loop termination

The for loop moves from the last index to index 0. After processing both characters, the loop ends and the final decimal value 26 is printed.

5. Hexadecimal digit values

Hexadecimal Digit Decimal Value
0 to 90 to 9
A or a10
B or b11
C or c12
D or d13
E or e14
F or f15

6. Why the loop moves from right to left

The rightmost hexadecimal digit has the smallest place value, 160. The next digit has place value 161, and so on. Therefore, processing from right to left allows the program to multiply the base by 16 after every digit.

7. Why base starts at 1

The rightmost digit is multiplied by 160, which equals 1. Therefore, base starts at 1. After each iteration, it becomes 16, then 256, then 4096, and so on.

8. Why input validation is important

A hexadecimal number can contain only 0-9, A-F, and a-f. If the user enters any other character, such as G or Z, the program displays an error message and stops conversion.

9. Manual conversion vs library function

The standard library function strtol(hex, NULL, 16) can also convert a hexadecimal string to decimal. This program performs the same conversion manually using a for loop, which helps you understand base conversion and character handling.

10. Complexity summary

If the hexadecimal string has n characters, the time complexity is O(n), because every character is processed once. Space complexity is O(1), because the program uses only a few variables and does not create additional arrays.

🎯 Remember this: Process the hexadecimal string from right to left, convert 0-9 and A-F into decimal values, multiply each value by the current power of 16, and add the results.

Frequently Asked Questions

1. What is the hexadecimal number system?

Hexadecimal is a base-16 number system. It uses digits 0 to 9 and letters A to F, where A represents 10 and F represents 15.

2. Why do we multiply by powers of 16?

Each hexadecimal digit has a place value based on powers of 16. The rightmost digit is multiplied by 160, the next by 161, the next by 162, and so on.

3. How is the letter A converted to 10?

For uppercase letters, the program calculates hex[i] - 'A' + 10. For example, 'A' - 'A' is 0, so adding 10 gives 10. Similarly, 'F' - 'A' + 10 gives 15.

4. Does the program accept lowercase hexadecimal letters?

Yes. The program accepts both uppercase and lowercase letters. For example, 1A and 1a both convert to decimal 26.

5. What happens if the user enters an invalid character?

If the input contains a character other than 0-9, A-F, or a-f, the program prints an error message and stops the conversion.

6. What is the time complexity of this program?

The time complexity is O(n), where n is the number of characters in the hexadecimal string. Each character is processed exactly once. Space complexity is O(1).

💡 Tip: After implementing this program, try converting a binary string to decimal. The logic is similar, but each digit is multiplied by powers of 2 instead of powers of 16.

📖 Related Tutorials

  • 16. Convert a Decimal Number to Octal Using a Do-While Loop
  • 17. Count the Number of 1s in the Binary Representation of an Integer Using a While Loop
  • 19. Print Pascal's Triangle Using Nested For Loops
  • All Loop Assignments in C

Previous Topic: -->> 17. Write a program in C to count the number of 1s in the binary representation of an integer using a while loop.   ||   Next Topic: -->> 19. Write a program in C to print Pascal's triangle using nested for loops.


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.