image

C Program to Convert Decimal to Binary Format (and Vice Versa)

In the world of computer programming, binary and decimal number systems play a crucial role. Binary numbers are the fundamental representation of data in digital computers, while decimal numbers are the conventional way humans represent and work with numbers. Converting between these two number systems is a fundamental operation in computer science and has numerous applications in various domains, including data communication, digital signal processing, and cryptography. In this article, we will explore how to write a C program that can convert decimal numbers to binary format and vice versa.

Understanding Binary and Decimal Number Systems

Before diving into the code, let's briefly review the binary and decimal number systems.

The binary number system is a base-2 positional numeral system that uses only two digits: 0 and 1. Each digit in a binary number represents a power of 2, with the rightmost digit representing 2^0 (1), the next digit to the left representing 2^1 (2), and so on.

On the other hand, the decimal number system is a base-10 positional numeral system that uses ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each digit in a decimal number represents a power of 10, with the rightmost digit representing 10^0 (1), the next digit to the left representing 10^1 (10), and so on.

Converting Decimal to Binary

To convert a decimal number to binary, we need to repeatedly divide the decimal number by 2 and record the remainders in reverse order until the quotient becomes 0.

Here's the step-by-step algorithm:

  1. Initialize an empty string or array to store the binary digits.
  2. Divide the decimal number by 2 and record the remainder (0 or 1) in the binary string/array.
  3. Replace the decimal number with the quotient obtained in step 2.
  4. Repeat steps 2 and 3 until the decimal number becomes 0.
  5. The binary string/array now contains the binary representation of the original decimal number, but in reverse order.
  6. Reverse the binary string/array to get the correct binary representation.

Here's the C program that implements this algorithm:

#include <stdio.h>

#include <string.h>

 

void decToBin(int dec, char *bin) {

    int i = 0;

    while (dec > 0) {

        bin[i++] = (dec % 2) + '0'// Store the remainder as a character

        dec /= 2;

    }

    bin[i] = '\0'// Null-terminate the string

    strrev(bin);  // Reverse the string to get the correct order

}

 

int main() {

    int decimal;

    char binary[33];  // Maximum length for a 32-bit integer

 

    printf("Enter a decimal number: ");

    scanf("%d", &decimal);

 

    decToBin(decimal, binary);

 

    printf("The binary representation is: %s\n", binary);

 

    return 0;

}

Converting Binary to Decimal

To convert a binary number to decimal, we need to multiply each binary digit by the corresponding power of 2 and sum the results.

Here's the step-by-step algorithm:

  1. Initialize a variable to store the decimal value, starting with 0.
  2. Iterate over each binary digit from right to left.
  3. For each binary digit, multiply it by the corresponding power of 2 and add the result to the decimal value.
  4. Increment the power of 2 for the next iteration.
  5. After iterating over all binary digits, the decimal value will contain the decimal representation of the original binary number.

Here's the C program that implements this algorithm:

#include <stdio.h>

#include <math.h>

#include <string.h>

 

int binToDec(char *bin) {

    int dec = 0, len = strlen(bin);

    for (int i = 0; i < len; i++) {

        if (bin[i] == '1') {

            dec += pow(2, len - i - 1);  // Multiply by the corresponding power of 2

        }

    }

    return dec;

}

 

int main() {

    char binary[33];  // Maximum length for a 32-bit integer

 

    printf("Enter a binary number: ");

    scanf("%s", binary);

 

    int decimal = binToDec(binary);

 

    printf("The decimal representation is: %d\n", decimal);

 

    return 0;

}

FAQs

What is the maximum decimal number that can be represented in a 32-bit integer?

The maximum decimal number that can be represented in a 32-bit signed integer is 2,147,483,647 (2^31 - 1). This limitation is due to the fixed size of 32 bits (4 bytes) used to store the integer value.

Can these programs handle negative numbers?

The programs presented in this article assume that the input is a non-negative integer. To handle negative numbers, additional logic would need to be implemented to account for the sign and perform the appropriate operations.

Why is the binary string/array null-terminated in the decToBin function?

The binary string/array is null-terminated to ensure that it is treated as a valid C string. This allows the use of string functions like strrev and facilitates printing the binary representation using printf("%s", binary).

How can I extend these programs to handle larger numbers?

To handle larger numbers, you can use data types with larger bit sizes, such as long long (64 bits) or arbitrary-precision arithmetic libraries like GMP (GNU Multiple Precision Arithmetic Library). However, these approaches may require additional modifications to the code and introduce more complexity.

Can these programs handle binary or decimal numbers with leading zeros?

The programs presented in this article assume that the input does not contain leading zeros. To handle inputs with leading zeros, additional input validation and preprocessing would be required to remove the leading zeros before performing the conversion.

What is the time complexity of these conversion algorithms?

Both the decimal-to-binary and binary-to-decimal conversion algorithms have a time complexity of O(n), where n is the number of digits in the input number. This means that the time required to perform the conversion grows linearly with the size of the input.

Can these programs handle other number systems, like hexadecimal or octal?

Yes, these programs can be extended to handle other number systems by modifying the conversion algorithms and adjusting the base used for division or multiplication. For example, to convert decimal to hexadecimal, the base would be 16 instead of 2.

What are some practical applications of binary-decimal conversion?

Binary-decimal conversion has numerous practical applications in computer science and related fields. Some examples include:

  • Data communication and networking protocols
  • Digital signal processing and audio/video encoding
  • Cryptography and data encryption
  • Low-level programming and system programming
  • Computer architecture and hardware design
Share On