Convert Numbers Between Bases in C

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to convert numbers between different bases using C programming. The lab covers the following steps:

  1. Read the number and target base from the user input.
  2. Implement the conversion algorithm using division and remainders to convert the decimal number to the target base.
  3. Print the converted number.

The lab provides a step-by-step guide to develop a base conversion program in C, covering the necessary concepts from number theory and discrete mathematics.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/strings("`Strings`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435169{{"`Convert Numbers Between Bases in C`"}} c/variables -.-> lab-435169{{"`Convert Numbers Between Bases in C`"}} c/operators -.-> lab-435169{{"`Convert Numbers Between Bases in C`"}} c/for_loop -.-> lab-435169{{"`Convert Numbers Between Bases in C`"}} c/strings -.-> lab-435169{{"`Convert Numbers Between Bases in C`"}} c/user_input -.-> lab-435169{{"`Convert Numbers Between Bases in C`"}} c/math_functions -.-> lab-435169{{"`Convert Numbers Between Bases in C`"}} end

Read the Number and Target Base

In this step, we'll learn how to read a number and its target base for conversion in C programming. We'll create a simple program that allows users to input a decimal number and specify the base they want to convert it to.

First, let's create a new C file for our base conversion program:

cd ~/project
nano base_converter.c

Now, let's write the initial code to read the number and target base:

#include <stdio.h>

int main() {
    int number, base;

    // 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;
    }

    printf("Number entered: %d\n", number);
    printf("Target base: %d\n", base);

    return 0;
}

Let's 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): 2
Number entered: 42
Target base: 2

Code Explanation:

  • We use scanf() to read the decimal number and target base from user input
  • We validate the base to ensure it's between 2 and 16 (supporting binary to hexadecimal)
  • The program prints back the entered number and base to confirm input

Convert Using Division and Remainders

In this step, we'll implement the core algorithm for converting a decimal number to another base using division and remainders. We'll modify our previous program to add the conversion logic.

Open the existing file and update the code:

cd ~/project
nano base_converter.c

Replace the previous code with the following implementation:

#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";

    // 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;
    }
}

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 and print the result
    convertToBase(number, base, result);

    printf("Decimal %d in base %d is: %s\n", 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): 2
Decimal 42 in base 2 is: 101010

Enter a decimal number to convert: 255
Enter the target base (2-16): 16
Decimal 255 in base 16 is: FF

Code Explanation:

  • convertToBase() function implements the core conversion algorithm
  • Uses division and remainder to extract digits from right to left
  • Supports bases from 2 to 16 using a predefined digit set
  • Handles special case of 0
  • Reverses the result string to get correct digit order
  • Uses an array of digits to map remainders to corresponding base characters

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

Summary

In this lab, we learned how to read a number and its target base for conversion in C programming. We created a simple program that allows users to input a decimal number and specify the base they want to convert it to. We also implemented the core algorithm for converting a decimal number to another base using division and remainders. Finally, we learned how to print the converted number in the desired base.

The key learning points from this lab include understanding how to use the scanf() function to read user input, validating the input to ensure the target base is within the valid range, and implementing the base conversion logic using division and remainders. The program demonstrates a practical application of these concepts in C programming.

Other C Tutorials you may like