C Online Compiler
Example: Decimal to Hexadecimal Converter using Custom Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Decimal to Hexadecimal Converter using Custom Function #include <stdio.h> // For printf #include <string.h> // For string manipulation (optional for manual reverse) // Function to convert a decimal number to hexadecimal string // Stores the result in the provided char array 'hexResult' void decimalToHex(int decimalNum, char hexResult[]) { int i = 0; // Handle the case where the decimal number is 0 separately if (decimalNum == 0) { hexResult[i++] = '0'; hexResult[i] = '\0'; return; } while (decimalNum > 0) { int remainder = decimalNum % 16; if (remainder < 10) { // Convert 0-9 to ASCII '0'-'9' hexResult[i++] = remainder + '0'; } else { // Convert 10-15 to ASCII 'A'-'F' hexResult[i++] = remainder + 'A' - 10; } decimalNum /= 16; // Divide by 16 for the next digit } hexResult[i] = '\0'; // Null-terminate the string // The hexadecimal digits are accumulated in reverse order // (least significant digit first), so we need to reverse the string. int start = 0; int end = i - 1; while (start < end) { char temp = hexResult[start]; hexResult[start] = hexResult[end]; hexResult[end] = temp; start++; end--; } } int main() { int decimal1 = 255; char hexResult1[100]; // Buffer to store the hexadecimal string decimalToHex(decimal1, hexResult1); printf("Decimal %d -> Hexadecimal %s\n", decimal1, hexResult1); int decimal2 = 10; char hexResult2[100]; decimalToHex(decimal2, hexResult2); printf("Decimal %d -> Hexadecimal %s\n", decimal2, hexResult2); int decimal3 = 256; char hexResult3[100]; decimalToHex(decimal3, hexResult3); printf("Decimal %d -> Hexadecimal %s\n", decimal3, hexResult3); int decimal4 = 0; char hexResult4[100]; decimalToHex(decimal4, hexResult4); printf("Decimal %d -> Hexadecimal %s\n", decimal4, hexResult4); int decimal5 = 4096; char hexResult5[100]; decimalToHex(decimal5, hexResult5); printf("Decimal %d -> Hexadecimal %s\n", decimal5, hexResult5); return 0; }
Output
Clear
ADVERTISEMENTS