C Program to Convert Decimal to Hexadecimal

Converting numbers from one base to another is a fundamental concept in computer science. In this article, we will delve into how to write a C program to convert decimal to hexadecimal using three different methods. Hexadecimal (base-16) is often used in computing due to its concise representation of binary data. This article will cover three methods to achieve this conversion, each with clear explanations, code examples, and output. You can also refer to our complete guide to learn how to convert Decimal to Binary, Binary to Decimal, and Hexadecimal to Decimal.

C Program to Convert Decimal to Hexadecimal: A Complete Guide

Introduction to Decimal and Hexadecimal Systems

Before diving into the conversion methods, let’s briefly understand the decimal and hexadecimal numbering systems.

Decimal System

The decimal system (base-10) is the standard system for denoting integer and non-integer numbers. It consists of 10 digits: 0 to 9.

Hexadecimal System

The hexadecimal system (base-16) extends the decimal system by adding six additional symbols, represented by the letters A to F. In hexadecimal:

  • A = 10
  • B = 11
  • C = 12
  • D = 13
  • E = 14
  • F = 15

Now, let’s explore how to convert a decimal number to hexadecimal in C.

Method 1) C Program to Convert Decimal to Hexadecimal Using Repeated Division

The most common method to convert a decimal number to hexadecimal is by repeatedly dividing the number by 16 and recording the remainders. These remainders represent the hexadecimal digits in reverse order.

Code Example

#include <stdio.h>

void decimalToHexadecimal(int decimal) {
    char hexadecimal[100];
    int index = 0;

    while (decimal != 0) {
        int remainder = decimal % 16;

        if (remainder < 10) {
            hexadecimal[index] = 48 + remainder; // 48 is the ASCII value for '0'
        } else {
            hexadecimal[index] = 55 + remainder; // 55 is the ASCII value for 'A'
        }

        decimal = decimal / 16;
        index++;
    }

    // Print the hexadecimal number in reverse order
    printf("Hexadecimal: ");
    for (int i = index - 1; i >= 0; i--) {
        printf("%c", hexadecimal[i]);
    }
    printf("\n");
}

int main() {
    int decimal;
    printf("Enter a decimal number: ");
    scanf("%d", &decimal);
    decimalToHexadecimal(decimal);
    return 0;
}

Explanation

  • Input: The program prompts the user to enter a decimal number.
  • Process: The program repeatedly divides the number by 16. The program stores the remainder as a character, either a digit (0-9) or a letter (A-F), based on its value.
  • Output: The program stores the hexadecimal digits in reverse order and prints them backward to produce the correct hexadecimal number.t hexadecimal number.

Output

Enter a decimal number: 255
Hexadecimal: FF

Method 2) C Program to Convert Decimal to Hexadecimal Using Recursion

Recursion is another elegant way to perform the conversion. The function avoids looping by calling itself with the reduced number until it reaches the base case.

Code Example

#include <stdio.h>

void decimalToHexadecimalRecursive(int decimal) {
    if (decimal == 0) {
        return;
    }

    int remainder = decimal % 16;
    decimalToHexadecimalRecursive(decimal / 16);

    if (remainder < 10) {
        printf("%c", 48 + remainder);
    } else {
        printf("%c", 55 + remainder);
    }
}

int main() {
    int decimal;
    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    printf("Hexadecimal: ");
    if (decimal == 0) {
        printf("0");
    } else {
        decimalToHexadecimalRecursive(decimal);
    }
    printf("\n");

    return 0;
}

Explanation

  • Input: The program prompts the user to enter a decimal number.
  • Process: The function calls itself with the quotient of the number divided by 16. The base case is when the decimal becomes 0.
  • Output: The program prints the hexadecimal digits in the correct order as the recursive calls unwind.

Output

Enter a decimal number: 4095
Hexadecimal: FFF

Method 3) C Program to Convert Decimal to Hexadecimal Using sprintf Function

C provides a built-in function, sprintf, that can convert a decimal number to a hexadecimal string. This method is the simplest and most concise, relying on C’s standard library.

Code Example

#include <stdio.h>

int main() {
    int decimal;
    char hexadecimal[100];

    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    sprintf(hexadecimal, "%X", decimal);
    printf("Hexadecimal: %s\n", hexadecimal);

    return 0;
}

Explanation

  • Input: The program takes a decimal number from the user.
  • Process: The sprintf function formats the decimal number into a hexadecimal string using the %X format specifier.
  • Output: The program directly prints the hexadecimal representation.

Output

Enter a decimal number: 1024
Hexadecimal: 400

Frequently Asked Questions (FAQs)

1) What is the difference between decimal and hexadecimal number systems?

The decimal system is base-10, using digits from 0 to 9, while the hexadecimal system is base-16, using digits from 0 to 9 and letters from A to F (where A = 10, B = 11, …, F = 15).

2) Why is hexadecimal used in computing?

Computing uses hexadecimal because it provides a more compact way to represent binary data. One hexadecimal digit represents four binary digits (bits), making it easier to read and debug low-level code like memory addresses or color codes.

3) How do I convert a decimal number to hexadecimal manually?

To convert manually, divide the decimal number by 16, record the remainder, and repeat with the quotient until you get zero. The remainders give the hexadecimal digits, read from bottom to top.

4) What are some real-world applications of hexadecimal numbers?

Hexadecimal is widely used in:

  • Memory addresses
  • Color codes in web design (e.g., #FFFFFF for white)
  • Error codes in debugging
  • Machine-level programming and assembly language

5) Can I use a loop to convert decimal to hexadecimal in C?

Yes, you can use a loop to repeatedly divide the decimal number by 16 and store the remainders as hexadecimal digits. The first method described in this article uses a loop for this purpose.

6) How does the sprintf function work for hexadecimal conversion in C?

The sprintf function formats a string based on the provided format specifier. For hexadecimal conversion, %X is used to format the decimal number into an uppercase hexadecimal string, while %x gives a lowercase result.

7) What is the advantage of using recursion for decimal to hexadecimal conversion?

Recursion provides an elegant solution, reducing the need for external data structures like arrays. The function calls itself until it reaches the base case, producing the hexadecimal digits in the correct order during the unwinding phase.

8) What happens if I input zero in a decimal to hexadecimal converter?

If you input 0, the hexadecimal equivalent is also 0. All the methods discussed in this article handle this edge case effectively by checking for the value before performing any conversions.

9) Can I convert negative decimal numbers to hexadecimal in C?

You can convert negative decimal numbers to hexadecimal by using two’s complement notation for negative integers. However, handling negative numbers requires additional logic since hexadecimal representations of signed integers vary in implementation.

10) Is there a built-in function in C to convert decimal to hexadecimal?

There isn’t a direct built-in function for conversion, but you can use sprintf to format the decimal number as hexadecimal. For more control, you can implement your conversion logic using loops or recursion as shown in this article.

Converting decimal numbers to hexadecimal is a fundamental concept in C programming, especially when working with low-level data representation. In this article, we explored three methods to perform the conversion:

  1. Using Repeated Division: A manual and efficient approach.
  2. Using Recursion: An elegant solution for solving the problem with less manual intervention.
  3. Using sprintf Function: The simplest method leveraging C’s standard library functions.

Each method has its advantages, and depending on your requirements, you can choose the one that best fits your application. Understanding how to work with different number systems is an essential skill in C programming, particularly when dealing with system-level programming or debugging.

By implementing these techniques, you’ll gain a deeper understanding of number systems and sharpen your C programming skills.

Categories C

Leave a Comment