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

// Function to convert binary to decimal
int binaryToDecimal(const char *binary) {
    int decimal = 0;  // Variable to store the decimal result
    int length = strlen(binary);  // Get the length of the binary string

    // Loop through each character in the binary string
    for (int i = 0; i < length; i++) {
        // Get the bit value (0 or 1) by converting character to integer
        int bit = binary[length - 1 - i] - '0';
        
        // Add the decimal value of the current bit
        decimal += bit * pow(2, i);
    }

    return decimal;  // Return the computed decimal value
}

int main() {
    char binary[65];  // Array to hold binary input (up to 64 bits + null terminator)

    printf("Enter a binary number: ");
    scanf("%64s", binary);  // Read the binary input (up to 64 characters)

    int decimal = binaryToDecimal(binary);  // Call the conversion function
    printf("Decimal equivalent: %d\n", decimal);  // Print the result

    return 0;  // Indicate successful completion
}

Explanation:

  1. Binary Representation:
    • In binary, each digit represents a power of 2. For example, in the binary number 1011:
      • 1×23+0×22+1×21+1×20=8+0+2+1=111 \times 2^3 + 0 \times 2^2 + 1 \times 2^1 + 1 \times 2^0 = 8 + 0 + 2 + 1 = 111×23+0×22+1×21+1×20=8+0+2+1=11.
    • This means that each bit contributes a specific value based on its position.
  2. Decimal Representation:
    • The decimal system uses ten digits (0-9), and each digit’s position represents a power of 10.

Program Structure

  1. Includes and Libraries:
    • The program begins by including necessary libraries:
      • stdio.h for standard input and output.
      • string.h for string manipulation functions.
      • math.h for mathematical functions like powers.
  2. Function Definition:
    • A function called binaryToDecimal is defined to perform the conversion. It takes a string input representing a binary number and processes it to compute the decimal value.
  3. Input Handling:
    • The main function prompts the user to enter a binary number, reads the input, and stores it in a character array.
  4. Conversion Logic:
    • The function calculates the decimal value by iterating through each character of the binary string:
      • It accesses each bit from right to left, converts it from a character to an integer, and computes its contribution to the decimal total based on its position.
      • This is done using the formula bit×2positionbit \times 2^{position}bit×2position.
  5. Output:
    • Once the conversion is complete, the program prints the decimal equivalent of the entered binary number.

Output

Enter a binary number: 1011
Decimal equivalent: 11

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights