Print the Converted Number
In this final step, we'll enhance our base conversion program by adding more comprehensive output and formatting options to display the converted number.
Open the existing file and update the code:
cd ~/project
nano base_converter.c
Update the code with improved printing and formatting:
#include <stdio.h>
#include <string.h>
// Function to convert decimal to any base
void convertToBase(int number, int base, char *result) {
int index = 0;
char digits[] = "0123456789ABCDEF";
int original = number; // Store original number for display
// Handle special case of 0
if (number == 0) {
result[index++] = '0';
result[index] = '\0';
return;
}
// Convert using division and remainders
while (number > 0) {
int remainder = number % base;
result[index++] = digits[remainder];
number = number / base;
}
// Reverse the string
result[index] = '\0';
for (int i = 0, j = index - 1; i < j; i++, j--) {
char temp = result[i];
result[i] = result[j];
result[j] = temp;
}
}
// Function to print detailed conversion information
void printConversionInfo(int decimal, int base, const char *converted) {
printf("\n--- Number Conversion Details ---\n");
printf("Original Number (Decimal): %d\n", decimal);
printf("Target Base: %d\n", base);
printf("Converted Number: %s\n", converted);
// Additional base representations
printf("\nBase Representations:\n");
printf(" Decimal: %d\n", decimal);
// Binary representation
if (base != 2) {
char binaryResult[33];
convertToBase(decimal, 2, binaryResult);
printf(" Binary: %s\n", binaryResult);
}
// Hexadecimal representation
if (base != 16) {
char hexResult[9];
convertToBase(decimal, 16, hexResult);
printf(" Hexadecimal: %s\n", hexResult);
}
}
int main() {
int number, base;
char result[33]; // Max 32 bits + null terminator
// Prompt user to enter the decimal number
printf("Enter a decimal number to convert: ");
scanf("%d", &number);
// Prompt user to enter the target base
printf("Enter the target base (2-16): ");
scanf("%d", &base);
// Validate base input
if (base < 2 || base > 16) {
printf("Invalid base. Please enter a base between 2 and 16.\n");
return 1;
}
// Convert the number
convertToBase(number, base, result);
// Print detailed conversion information
printConversionInfo(number, base, result);
return 0;
}
Compile and run the program:
gcc base_converter.c -o base_converter
./base_converter
Example output:
Enter a decimal number to convert: 42
Enter the target base (2-16): 16
--- Number Conversion Details ---
Original Number (Decimal): 42
Target Base: 16
Converted Number: 2A
Base Representations:
Decimal: 42
Binary: 101010
Hexadecimal: 2A
Code Explanation:
- Added
printConversionInfo()
function to provide detailed conversion output
- Displays original decimal number, target base, and converted result
- Includes additional base representations (binary and hexadecimal)
- Conditionally prints alternative base representations to avoid redundancy
- Provides a more informative and educational output