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