C Program to convert a decimal number to a hexadecimal number
Last updated on September 24, 2020
The following is a C program to convert a decimal number to a binary number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | /************************************************************
Program to convert a decimal number to a hexadecimal number
************************************************************/
#include<stdio.h> // include stdio.h library
int main(void)
{
int num, bin = 0;
int i = 0, rem;
char hex_arr[50];
printf("Enter a decimal number: ");
scanf("%d", &num);
while(num != 0)
{
rem = num % 16; // get the right most digit
if (rem < 10)
{
hex_arr[i++] = 48 + rem;
}
else
{
hex_arr[i++] = 55 + rem;
}
num /= 16; // get the quotient
}
printf("0x");
for(int j = i - 1; j >= 0 ; j--) // print the hex_arr in reverse order
{
printf("%c", hex_arr[j]);
}
return 0; // return 0 to operating system
}
|
Expected Output: 1st run:
1 2 | Enter a decimal number: 198
0xC6
|
2nd run:
1 2 | Enter a decimal number: 123456
0x1E240
|
How it works #
To convert a decimal number to a hexadecimal number, we follow these steps:
Step 1: Divide the decimal number continuously by 16 and write the remainder on the right-hand side of the dividend. We repeat this process until we get the quotient 0.
Step 2: If the remainder is greater than 10, then replace it with a hexadecimal character given in the table below:
Decimal | Hexadecimal |
---|---|
10 |
A |
11 |
B |
12 |
C |
13 |
D |
14 |
E |
15 |
F |
Step 3: Write the remainders from bottom to top.
Let's take some examples:
Example 1: Convert decimal 210 to hexadecimal number.
Step 1:
Quotient | Remainder | |
---|---|---|
210/16 |
13 |
2 |
13/16 |
0 |
13 |
Step 2:
Quotient | Remainder | Hexadecimal | |
---|---|---|---|
210/16 |
13 |
2 |
2 |
13/16 |
0 |
13 |
D |
Step 3:
\(\mathtt{210_{10} = 0xD2_{16}}\)
Example 2:
Convert decimal 100 to a hexadecimal number.
Step 1:
Quotient | Remainder | |
---|---|---|
100/16 |
6 |
4 |
6/16 |
0 |
6 |
Step 2: In this case, both the remainders are smaller than 10, so we don't need to replace them with the hexadecimal characters.
Step 3:
\(\mathtt{100_{10} = 0x64_{16}}\)
The following table shows what happens at each iteration of the loop (assuming num = 198
):
Iteration | rem | hex_arr | num | i |
---|---|---|---|---|
After 1st iteration | rem=198%16=6 |
hex_arr[0]=48+6=54 |
num=198/16=12 |
i=1 |
After 2nd iteration | rem=12%16=12 |
hex_arr[1]=55+12=67 |
num=12/16=0 |
i=2 |
Recommended Reading
- C Program to convert a decimal number to an octal number
- C Program to convert a decimal number to a binary number
- C Program to Convert a Binary Number to a Decimal Number
- C Program to multiply two numbers using Russian peasant method
- C Program to check whether the number is a Palindrome
Load Comments