Here we will build a C Program For Decimal to Hexadecimal Conversion using 4 different approaches i.e.
- Using format specifier
- Using modulus division operator
- Without using the modulus division operator
- Using Functions
We will keep the same input in all the mentioned approaches and get an output accordingly.
Input:
decimal number = 45
Output:
hexadecimal number = 2D
Method 1: Using the format specifier %X
C
#include <stdio.h>
int main()
{
int decimalNumber = 45;
printf ( "Hexadecimal number is: %X" , decimalNumber);
return 0;
}
|
Output
Hexadecimal number is: 2D
Method 2: Using the modulus division operator
C
#include <stdio.h>
int main()
{
int decimal_Number = 45;
int i = 1, j, temp;
char hexa_Number[100];
while (decimal_Number != 0) {
temp = decimal_Number % 16;
if (temp < 10)
temp = temp + 48;
else
temp = temp + 55;
hexa_Number[i++] = temp;
decimal_Number = decimal_Number / 16;
}
printf ( "Hexadecimal value is: " );
for (j = i - 1; j > 0; j--)
printf ( "%c" , hexa_Number[j]);
return 0;
}
|
Output
Hexadecimal value is: 2D
Method 3: Without using modulus division
C
#include <stdio.h>
int main()
{
int decimal_Number = 45;
int i = 1, j, temp;
char hexa_Number[100];
while (decimal_Number != 0) {
int ch = decimal_Number / 16;
int r = ch * 16;
temp = decimal_Number - r;
if (temp < 10)
temp = temp + 48;
else
temp = temp + 55;
hexa_Number[i++] = temp;
decimal_Number = decimal_Number / 16;
}
printf ( "Hexadecimal value is: " );
for (j = i - 1; j > 0; j--)
printf ( "%c" , hexa_Number[j]);
return 0;
}
|
Output
Hexadecimal value is: 2D
Method 4: Using functions
C
#include <stdio.h>
int dec_to_hexa_conversion( int decimal_Number)
{
int i = 1, j, temp;
char hexa_Number[100];
while (decimal_Number != 0) {
temp = decimal_Number % 16;
if (temp < 10)
temp = temp + 48;
else
temp = temp + 55;
hexa_Number[i++] = temp;
decimal_Number = decimal_Number / 16;
}
printf ( "Hexadecimal value is: " );
for (j = i - 1; j > 0; j--)
printf ( "%c" , hexa_Number[j]);
}
int main()
{
int Number = 45;
dec_to_hexa_conversion(Number);
return 0;
}
|
Output
Hexadecimal value is: 2D
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
02 Aug, 2022
Like Article
Save Article