How To Convert Binary To Decimal In C

Programmers frequently have to convert binary numbers to decimal numbers, particularly when dealing with low-level operations or transforming data across formats.

Decimal is a base-10 number system that employs ten digits, whilst binary is a base-2 number system that only uses two digits (0 and 1). (0 to 9).

In this blog post, we’ll learn how to convert binary to decimal in C and offer a classification process to show how it’s done.

Why there is need to convert binary to decimal

Need to convert binary to decimal is for displaying the binary number in a more readable format. While binary is useful for computers to store and manipulate data, it can be difficult for humans to read and interpret.

Converting a binary number to decimal allows you to display the value in a more familiar format that is easier for humans to understand.

Here are some reasons why there is need to convert binary to decimal in c language:

  1. Binary numbers are hard for human beings to read and comprehend, particularly when dealing with prolonged sequences of digits. On the other hand, decimal numbers are more simple for people to comprehend and are the standard number system used in daily life. We can represent a binary number in decimal form to make it simpler for individuals to understand.
  2. Data manipulation: Binary format is frequently used in computer programming to store and modify data. Nonetheless, there are instances when we must use decimal numbers to conduct arithmetic or logical operations on this data. In these circumstances, binary data must first be converted to decimal format.
  3. Various systems may represent data using numerous different number systems during system communication. For instance, a microcontroller could perhaps represent sensor readings as binary numbers, whereas a computer programme might process the same data as decimal numbers. It might be essential to transform the data to the appropriate number system prior to actually sending it between these systems.
  4. Testing and debugging: It might be challenging to manually check that binary data is accurate when working with binary data. We can quickly validate the data using common decimal arithmetic by converting the binary data to decimal representation.

So these are the needs to learn how to convert binary to decimal in C.

Different approaches to convert binary to decimal

  1. Using a loop
  • Using recursion
  • Using the bit-shift operator

These are the three different approaches to convert binary to decimal in C.

Detailed explanation

1. Using loop:

This approach involves iterating through each digit of the binary number using a loop and multiplying it by the appropriate power of 2 to obtain the decimal equivalent.

Sample code:

#include <stdio.h>

int main() {
    int binary, decimal = 0, base = 1, rem; // declare variables
    
    printf("Enter a binary number: "); // prompt user for input
    scanf("%d", &binary); // take input from user
    
    while (binary != 0) { // loop until binary becomes 0
        rem = binary % 10; // extract rightmost digit
        decimal += rem * base; // add to decimal equivalent
        binary /= 10; // remove rightmost digit
        base *= 2; // move to next bit
    }
    
    printf("Decimal equivalent: %d\n", decimal); // print decimal equivalent
    
    return 0; // exit program
}

Output:

Enter a binary number: 1010
Decimal equivalent: 10

Code Explanation:

  1. Include the header file stdio.h for input and output operations.
  2. Define the main function.
  3. Declare three integer variables binary, decimal, and base and initialize decimal and base to 0 and 1 respectively.
  4. Prompt the user to enter a binary number using printf.
  5. Take binary input from the user using scanf and store it in the variable binary.
  6. While the binary number is not equal to 0, perform the following operations:
    a. Extract the rightmost digit of the binary number using the modulo operator % and store it in the variable rem.
    b. Add the product of rem and base to decimal.
    c. Divide the binary number by 10 to remove the rightmost digit.
    d. Multiply the base by 2 to move to the next bit.
  7. Once the loop completes, print the decimal equivalent to the console using printf.
  8. Exit the program by returning 0 from the main function.

2.Using recursion:

In the recursive method, extract the rightmost bit and add its decimal value to the result, and then call the function again with the remaining bits until the binary number becomes zero.

Code:

#include <stdio.h>
#include <math.h>

int binaryToDecimal(int binary, int index) {
    if(binary == 0) { // base case - when the binary number becomes 0
        return 0;
    }
    else {
        int rem = binary % 10; // extract the rightmost digit from binary number
        return (rem * pow(2, index)) + binaryToDecimal(binary/10, index+1); 
        // calculate the decimal value of the extracted digit and call binaryToDecimal recursively for the remaining digits
        // the parameter "index" keeps track of the position of the digit in the binary number
    }
}

int main() {
    int binaryNumber;
    printf("Enter a binary number: ");
    scanf("%d", &binaryNumber);
    int decimalNumber = binaryToDecimal(binaryNumber, 0); // call binaryToDecimal function with initial index value 0
    printf("Decimal equivalent: %d\n", decimalNumber);
    return 0;
}

Output:

Enter a binary number: 1010
Decimal equivalent: 10

Code Explanation:

  1. Include the header files stdio.h and math.h.
  2. Define the recursive function binaryToDecimal which takes two arguments – the binary number and the index of the bit currently being processed.
  3. In the function, check if the binary number is equal to 0. If it is, return 0 as the base case has been reached.
  4. Otherwise, extract the rightmost digit of the binary number using the modulo operator % and store it in the variable rem.
  5. Calculate the decimal equivalent of the rightmost bit by multiplying rem with 2 raised to the power of the index.
  6. Recursively call the binaryToDecimal function with the binary number without the rightmost bit and the index incremented by 1, and add the result to the decimal equivalent of the rightmost bit.
  7. In the main function, prompt the user to enter a binary number and take input using scanf.
  8. Call the binaryToDecimal function with the binary number and index initialized to 0 and store the result in the variable decimalNumber.
  9. Print the decimal equivalent to the console using printf.
  10. Exit the program by returning 0 from the main function.

3. Using the bit-shift operator:

In C programming, we can convert binary to decimal using the bitwise shift operators. We shift the bits of the binary number to the left and add the result to the decimal equivalent.

Code:

#include <stdio.h>

// Function to convert binary to decimal
int binaryToDecimal(int binary) {
    int decimal = 0, base = 1;
    // Loop through each bit of the binary number
    while (binary > 0) {
        // Extract the rightmost bit using bitwise AND operator with 1
        // and add the result to the decimal number
        decimal += (binary & 1) * base;
        // Right shift the binary number by 1 to get the next bit
        binary >>= 1;
        // Multiply the base by 2 for the next bit
        base *= 2;
    }
    // Return the decimal equivalent of the binary number
    return decimal;
}

int main() {
    int binaryNumber;
    // Read the binary number from the user
    printf("Enter a binary number: ");
    scanf("%d", &binaryNumber);
    // Convert the binary number to decimal using bitshift operator method
    int decimalNumber = binaryToDecimal(binaryNumber);
    // Print the decimal equivalent
    printf("Decimal equivalent: %d\n", decimalNumber);
    return 0;
}

Output:

Enter a binary number: 10101
Decimal equivalent: 21

Code Explanation:

  1. Define a function named binaryToDecimal which takes a binary number as input and returns its decimal equivalent.
  2. Initialize two variables decimal and base to 0 and 1 respectively. These variables will be used to store the decimal equivalent and the base value of each digit position.
  3. Enter a while loop that continues until the binary number becomes zero.
  4. In each iteration of the loop, bitwise AND the binary number with 1 to extract the rightmost bit of the binary number. If the bit is 1, add the current base value to the decimal equivalent.
  5. Right shift the binary number by 1 to discard the rightmost bit, and multiply the base value by 2 to move to the next bit position.
  6. When the binary number becomes zero, exit the loop and return the decimal equivalent.
  7. Define the main function.
  8. Declare a variable named binaryNumber to store the input binary number.
  9. Prompt the user to enter the binary number.
  10. Read the input binary number using the scanf function.
  11. Call the binaryToDecimal function with the input binary number as argument to convert it to decimal.
  12. Print the decimal equivalent using the printf function.
  13. Return 0 to indicate successful program execution.

Best Approach out of three

The optimal approach for converting binary to decimal in the C programming language depends on an assortment of variables, including that of the project’s specific requirements, the developer’s preferences, and performance concerns.

Due to the utilisation of bit manipulation operations, the bit-shift method is, nonetheless, frequently considered to be the most efficient and quick way. Although easier to comprehend and more elegant, the recursive approach might not be as effective for huge inputs. Although the loop method is clear-cut and simple to comprehend, it may not be nearly as concise as the bitwise way.

This method has good benefits over other methods and this is considered as an ideal approach to perform how to convert from binary to decimal in C.

These are:

  1. Efficiency: The shift operator, employed in the bitwise approach, performs operations more quickly than the division and modulo operations used in other methods. In circumstances where the conversion must be carried out repeatedly or for huge numbers, this can significantly affect performance.
  2. Simplicity: Compared to other ways, the bitwise method takes fewer lines of code and is simpler to understand. It doesn’t involve any more complicated mathematical operations than simple bit manipulation and doesn’t involve recursion.
  3. Readability: The usage of bitwise operators, which are well-known in low-level programming, allows the bitwise technique to make the code more readable.
  4. Memory: Unlike some other methods that might need arrays or other data structures to store intermediate values, the bitwise method doesn’t require any additional memory to conduct the conversion.

Sample Problems

Sample Problem 1:

Write a C program to convert a binary number to its decimal equivalent using a loop method. The program should prompt the user to enter a binary number and display the corresponding decimal equivalent.

Code:

#include <stdio.h>

int main() {
    int binary, decimal = 0, base = 1, rem;
    
    // Prompt user to enter binary number and read input
    printf("Enter a binary number: ");
    scanf("%d", &binary);
    
    // Convert binary to decimal using loop method
    while (binary != 0) {
        rem = binary % 10;  // Get the rightmost digit of binary number
        decimal += rem * base;  // Multiply the digit with corresponding power of 2 and add to decimal
        binary /= 10;  // Remove the rightmost digit from binary
        base *= 2;  // Increase the power of 2 for next digit
    }
    
    // Display the decimal equivalent
    printf("Decimal equivalent: %d\n", decimal);
    
    return 0;
}

Solution:

  1. Declare the necessary variables for binary number, decimal equivalent, base, and remainder.
  2. Prompt the user to enter a binary number and read the input using scanf.
  3. Initialize decimal equivalent and base to 0 and 1, respectively.
  4. While the binary number is greater than 0, perform the following operations:
    a. Compute the remainder of binary number divided by 10.
    b. Multiply the remainder with base and add it to the decimal equivalent.
    c. Divide the binary number by 10 and multiply base by 2.
  5. Print the decimal equivalent using printf.
  6. End the program.

Output:

Enter a binary number: 101010
Decimal equivalent: 42

Sample Problem 2:

Write a C program that uses recursion to convert a binary number to its decimal equivalent. Your program should prompt the user to enter a binary number and then display its decimal equivalent.

Code:

#include <stdio.h>

// Function to convert binary number to decimal using recursion
int binaryToDecimal(int binary) {
    if (binary == 0) {  // Base case: binary number is 0
        return 0;
    } else {
        // Recursive case: binary number is not 0
        // Extract last digit of binary number and compute its decimal value
        int lastDigit = binary % 10;
        int decimalValue = lastDigit * 1;

        // Recursively compute the decimal value of the remaining digits
        int remainingDigits = binary / 10;
        int remainingDecimalValue = binaryToDecimal(remainingDigits);

        // Combine the decimal value of the last digit with the decimal value of the remaining digits
        int result = decimalValue + 2 * remainingDecimalValue;
        return result;
    }
}

int main() {
    int binary;

    // Prompt user to enter a binary number
    printf("Enter a binary number: ");
    scanf("%d", &binary);

    // Convert binary number to decimal using recursion
    int decimal = binaryToDecimal(binary);

    // Display the decimal equivalent of the binary number
    printf("Decimal equivalent of %d is %d\n", binary, decimal);

    return 0;
}

Solution:

  1. The program prompts the user to enter a binary number using printf() function and reads it using scanf() function. The binary number is stored in an integer variable called binary.
  2. The program calls a function called binaryToDecimal() and passes it the binary number as an argument.
  3. The binaryToDecimal() function takes an integer argument binary and returns the decimal equivalent of the binary number.
  4. Inside the binaryToDecimal() function, the first thing we check is whether the binary parameter is equal to zero. If it is, we return 0 as the decimal equivalent.
  5. If the binary is not zero, we extract the last digit of the binary number using the modulo operator % and compute the decimal value of that digit by multiplying it with 2 raised to the power of its position. We do this recursively for the remaining digits of the binary number by calling binaryToDecimal() function with the quotient of binary divided by 10.
  6. Finally, we add up the decimal values of each digit using the formula digit_value * 2^position, where digit_value is either 0 or 1 and position is the position of the digit within the binary number (starting from the rightmost digit with position 0). This gives us the final decimal value of the binary number.
  7. The binaryToDecimal() function returns the decimal value, which is then printed on the screen using printf() function in the main() function.

Output:

Enter a binary number: 10101
Decimal equivalent of 10101 is 21

Sample Problem 3:

Write a C program to convert a binary number represented as a 32-bit integer to its decimal equivalent using the bit shift operator method.

Code:

#include <stdio.h>

int main() {
    int binary = 0b11011010101110110000101001111011; // 32-bit binary number
    int decimal = 0; // initialize decimal value to zero
    int power = 1; // initialize power of 2 to zero
    
    // loop through each bit of the binary number from right to left
    for (int i = 0; i < 32; i++) {
        int bit = (binary >> i) & 1; // get the value of the current bit
        decimal += bit * power; // add the bit's value to the decimal value
        power *= 2; // increment the power of 2
    }
    
    printf("Binary: %d\nDecimal: %d", binary, decimal); // print the binary and decimal values
    return 0;
}

Solution:

  1. Define the binary number to be converted.
  2. Create a variable to store the decimal equivalent of the binary number.
  3. Create a variable to keep track of the current bit position.
  4. Use a loop to iterate through each bit of the binary number.
  5. Extract the current bit from the binary number using a bitwise AND operation and shift it to the correct position using a bitwise left shift operation.
  6. Add the shifted bit to the decimal number.
  7. Increment the bit position by 1.
  8. Repeat steps 4-7 until all bits have been processed.
  9. Print the decimal equivalent of the binary number.

Output:

Binary: 3624589323
Decimal: 3624589323

Conclusion:

We can utilise the bit shift operator method in C programming to translate a binary number to its decimal equivalent. The binary number’s bits can be looped through from right to left using the bit shift operator to obtain the value of the current bit.

The bit value can then be added to the decimal value after already being multiplied by the current power of 2.

Finally, we multiply the power of 2 by 2 to enhance it. Up until all of the binary number’s bits have been handled, this process was repeated.

In C programming, this technique offers a quick and efficient approach to convert binary to decimal. These methods can also be used to learn how to convert a binary number number to decimal in c++