Converting a decimal number to hexadecimal in C can be done using a simple algorithm. Hexadecimal is a base-16 number system, which means it uses 16 different symbols (0-9 and A-F) to represent values. To convert a decimal number to hexadecimal, we repeatedly divide the decimal number by 16 and keep track of the remainders, which represent the hexadecimal digits. We then reverse the order of the remainders to get the hexadecimal representation.
Here's a C program to convert a decimal number to hexadecimal with an example and the expected output:
#include <stdio.h>
void decimalToHexadecimal(int decimal) {
char hex[20]; // To store the hexadecimal representation
int index = 0;
while (decimal > 0) {
int remainder = decimal % 16;
// Convert remainder to hexadecimal digit
if (remainder < 10) {
hex[index] = remainder + '0';
} else {
hex[index] = remainder + 'A' - 10;
}
decimal /= 16;
index++;
}
// Print the hexadecimal number in reverse order
printf("Hexadecimal: ");
for (int i = index - 1; i >= 0; i--) {
printf("%c", hex[i]);
}
printf("\n");
}
int main() {
int decimalNumber = 255; // Example decimal number
decimalToHexadecimal(decimalNumber);
return 0;
}
In this program:
We define a function
decimalToHexadecimal
that takes an integerdecimal
as its argument.Inside the function, we use a character array
hex
to store the hexadecimal representation. We also use anindex
variable to keep track of the current position in thehex
array.We enter a
while
loop that continues until thedecimal
number becomes zero.In each iteration of the loop, we calculate the remainder when the
decimal
is divided by 16. This remainder is then converted to the corresponding hexadecimal digit and stored in thehex
array.We then update the
decimal
by performing integer division by 16 and increment theindex
to move to the next position in thehex
array.After the loop, we print the hexadecimal number in reverse order to get the correct representation.
Now, let's run the program with an example value, such as 255
:
Hexadecimal: FF
The output shows that the decimal number 255
is correctly converted to its hexadecimal representation, which is 'FF'
.