Open In App

Number System Conversion in C

Last Updated : 22 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Number system conversion is a fundamental concept in computer science and programming. It involves changing the representation of a number from one base to another, such as converting a decimal number to binary or a hexadecimal number to binary.

In this article, we will create a console program in the C language to perform various number system conversions. Our program will be capable of conversion between the following number systems:

  • Decimal to Binary
  • Binary to Decimal
  • Decimal to Octal
  • Octal to Decimal
  • Hexadecimal to Binary
  • Binary to Hexadecimal
Number System Conversion in C

 

Understanding Number System Conversions

Before we look into the C program, let’s discuss some of the commonly used number systems:

  • Decimal (Base 10): The decimal system is the most commonly used number system, consisting of digits 0 to 9. Each digit’s position represents a power of 10. For example, the decimal number 123 is represented as (1 * 102) + (2 * 101) + (3 * 100).
     
  • Binary (Base 2): The binary system consists of only two digits, 0 and 1. This system is mostly used as in machines where each digit’s position represents a power of 2. For example, the binary number 1101 is represented as (1 * 23) + (1 * 22) + (0 * 21) + (1 * 20).
     
  • Octal (Base 8): The octal system consists of digits 0 to 7. Each digit’s position represents a power of 8. For example, the octal number 53 is represented as (5 * 81) + (3 * 80).
     
  • Hexadecimal (Base 16): The hexadecimal system uses digits 0 to 9 and letters A to F (or a to f) to represent values from 0 to 15. Each digit’s position represents a power of 16. For example, the hexadecimal number 1A3 is represented as (1 * 162) + (10 * 161) + (3 * 160)

How the Program Work?

We define functions for decimal-to-binary, binary-to-decimal, and other mentioned conversions. These functions implement the standard method for the respective conversions.

In the main function, we display a menu of conversion options and ask the user to select one. Depending on the user’s choice, we take input and call the corresponding conversion function. The conversion functions perform the conversion and display the result.

C Program for Number System Conversion

C




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
void strrev(char*);
  
// Function to convert decimal to binary and return as a
// string
char* decimalToBinary(int decimal)
{
    // Allocate space for a 32-bit binary string + '\0'
    char* binary = (char*)malloc(33);
  
    int i = 0;
    // converting to binary
    while (decimal) {
        binary[i++] = '0' + (decimal & 1);
        decimal >>= 1;
    }
    binary[i] = '\0';
    strrev(binary);
    return binary;
}
  
// Function to convert binary to decimal and return as an
// integer
int binaryToDecimal(char binary[])
{
    int decimal = 0;
    int length = strlen(binary);
    for (int i = 0; i < length; i++) {
        decimal = decimal * 2 + (binary[i] - '0');
    }
    return decimal;
}
  
// Function to convert decimal to octal and return as a
// string
char* decimalToOctal(int decimal)
{
    // Allocate space for an octal string
    char* octal = (char*)malloc(12);
    if (octal == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    // Convert decimal to octal
    sprintf(octal, "%o", decimal);
    return octal;
}
// Function to convert octal to decimal and return as an
// integer
int octalToDecimal(char octal[])
{
    int decimal = 0;
    int length = strlen(octal);
    for (int i = 0; i < length; i++) {
        decimal = decimal * 8 + (octal[i] - '0');
    }
    return decimal;
}
  
// Function to convert hexadecimal to binary and return as a
// string
char* hexadecimalToBinary(char hex[])
{
    // converting hexadecimal string to integer
    unsigned int hexNum;
    sscanf(hex, "%x", &hexNum);
    // string to store binary number
    char binary[33] = "";
    // converting to hexadecimal
    int i = 0;
    while (hexNum) {
        binary[i++] = '0' + hexNum % 2;
        hexNum /= 2;
    }
    binary[i] = '\0';
    strrev(binary);
  
    return strdup(binary);
}
  
// Function to convert binary to hexadecimal and return as a
// string
char* binaryToHexadecimal(char binary[])
{
    // Pad the binary string with leading zeros to ensure
    // it's a multiple of 4
    int length = strlen(binary);
    int padding = (4 - (length % 4)) % 4;
    char paddedBinary[129];
    memset(paddedBinary, '0', padding);
    strcpy(paddedBinary + padding, binary);
    // Define a mapping of binary strings to their
    // hexadecimal representations
    char* binaryHexDigits[]
        = { "0000", "0001", "0010", "0011", "0100", "0101",
            "0110", "0111", "1000", "1001", "1010", "1011",
            "1100", "1101", "1110", "1111" };
    char hexadecimal[33] = ""; // Allocate space for an
                               // 8-digit hexadecimal string
    // Iterate through groups of 4 binary digits and convert
    // to hexadecimal
    for (int i = 0; i < length + padding; i += 4) {
        char group[5];
        strncpy(group, paddedBinary + i, 4);
        group[4] = '\0';
        // Find the corresponding hexadecimal digit
        for (int j = 0; j < 16; j++) {
            if (strcmp(group, binaryHexDigits[j]) == 0) {
                // Append the corresponding hexadecimal
                // digit
                char hexDigit[2];
                sprintf(hexDigit, "%X", j);
                strcat(hexadecimal, hexDigit);
                break;
            }
        }
    }
    return strdup(hexadecimal);
}
  
// driver code
int main()
{
    int choice;
    while (1) {
        printf("\nMenu:\n");
        printf("1. Decimal to Binary\n");
        printf("2. Binary to Decimal\n");
        printf("3. Decimal to Octal\n");
        printf("4. Octal to Decimal\n");
        printf("5. Hexadecimal to Binary\n");
        printf("6. Binary to Hexadecimal\n");
        printf("7. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
  
        if (choice == 7) {
            printf("Goodbye!\n");
            break;
        }
  
        char input[100]; // Buffer for user input
        switch (choice) {
        case 1:
            printf("Enter a decimal number: ");
            scanf("%d", &choice);
            char* result = decimalToBinary(choice);
            printf("Decimal to Binary: %s\n", result);
            free(result);
            break;
        case 2:
            printf("Enter a binary number: ");
            scanf("%s", input);
            int binaryResult = binaryToDecimal(input);
            printf("Binary to Decimal: %d\n", binaryResult);
            break;
        case 3:
            printf("Enter a decimal number: ");
            scanf("%d", &choice);
            result = decimalToOctal(choice);
            printf("Decimal to Octal: %s\n", result);
            free(result);
            break;
        case 4:
            printf("Enter an octal number: ");
            scanf("%s", input);
            int octalResult = octalToDecimal(input);
            printf("Octal to Decimal: %d\n", octalResult);
            break;
        case 5:
            printf("Enter a hexadecimal number: ");
            scanf("%s", input);
            result = hexadecimalToBinary(input);
            printf("Hexadecimal to Binary: %s\n", result);
            free(result);
            break;
        case 6:
            printf("Enter a binary number: ");
            scanf("%s", input);
            result = binaryToHexadecimal(input);
            printf("Binary to Hexadecimal: %s\n", result);
            free(result);
            break;
        default:
            printf("Invalid choice. Please enter a valid "
                   "option.\n");
        }
    }
  
    return 0;
}
  
// reversing string
void strrev(char* str)
{
    int i = 0;
    int j = strlen(str) - 1;
    while (i < j) {
        char c = str[i];
        str[i] = str[j];
        str[j] = c;
        i++;
        j--;
    }
}


Output

1. Decimal to Binary

Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 1
Enter a decimal number: 128
Decimal to Binary: 10000000

2. Binary to Decimal

Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 2
Enter a binary number: 10000000
Binary to Decimal: 128

3. Decimal to Octal

Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 3
Enter a decimal number: 100
Decimal to Octal: 144

4. Octal to Decimal

Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 4
Enter an octal number: 144
Octal to Decimal: 100

5. Hexadecimal to Binary

Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 5
Enter a hexadecimal number: a10
Hexadecimal to Binary: 101000010000

6. Binary to Hexadecimal

Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 6
Enter a binary number: 101000010000
Binary to Hexadecimal: A10

Conclusion

Number system conversions are essential concepts in computer science and programming. Understanding how to convert between different bases is valuable when working with binary data, networking, and low-level programming. The C program provided in this article is a starting point for learning and practicing number system conversions in a practical and interactive way.

Related Articles

To learn the concept behind the conversion, you can refer to these articles:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads