Program for Decimal to Hexadecimal Conversion in C

Decimal to Hexadecimal Conversion

Converting a decimal number to hexadecimal involves dividing the number by 16 and recording the remainder.

We will explore three methods to perform this conversion using C programming.

Method 1: Using Built-in Function

We use C's built-in function to convert decimal to hexadecimal.

#include <stdio.h>

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

Output:

Enter a decimal number: 255
Hexadecimal: FF

Method 2: Using Division by 16

We repeatedly divide the decimal number by 16 and store the remainders to get the hexadecimal equivalent.

#include <stdio.h>

void decimalToHexadecimal(int decimal) {
    char hex[20];
    int i = 0;
    while (decimal > 0) {
        int remainder = decimal % 16;
        hex[i++] = (remainder < 10) ? remainder + '0' : remainder - 10 + 'A';
        decimal /= 16;
    }
    printf("Hexadecimal: ");
    for (int j = i - 1; j >= 0; j--) {
        printf("%c", hex[j]);
    }
    printf("\n");
}

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

Output:

Enter a decimal number: 255
Hexadecimal: FF

Method 3: Using Recursion

We use recursion to convert decimal to hexadecimal.

#include <stdio.h>

void decimalToHexadecimalRecursive(int decimal) {
    if (decimal == 0) return;
    decimalToHexadecimalRecursive(decimal / 16);
    int remainder = decimal % 16;
    printf("%c", (remainder < 10) ? remainder + '0' : remainder - 10 + 'A');
}

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;
}
            

Output:

Enter a decimal number: 255
Hexadecimal: FF
Numbers

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

HCF - Highest Common Factor: C C++ Java Python

LCM - Lowest Common Multiple: C C++ Java Python

GCD - Greatest Common Divisor: C C++ Java Python

Binary to Decimal Conversion: C C++ Java Python

Octal to Decimal Conversion: C C++ Java Python

Hexadecimal to Decimal Conversion: C C++ Java Python

Decimal to Binary Conversion: C C++ Java Python

Decimal to Octal Conversion: C C++ Java Python

Decimal to Hexadecimal Conversion: C C++ Java Python

Binary to Octal Conversion: C C++ Java Python

Quadrants in which a given coordinate lies: C C++ Java Python

Addition of Two Fractions: C C++ Java Python

Calculate the Area of a Circle: C C++ Java Python

Convert Digit/Number to Words: C C++ Java Python

Finding Roots of a Quadratic Equation: C C++ Java Python