Binary to Decimal Converter

A binary number is a sequence of bits (binary digits – 0’s and 1’s) of the form BnBn-1……B1 B0, where each Bi is a bit. The decimal equivalent is calculated by Bn * 2n+ Bn-1 * 2n-1 + … + B1 * 2 + B0. Write a program to input a binary number and output the decimal equivalent. The sample input will not have more than 8 individual bits (i.e., the largest value to be entered is 11111111).

Example 1:

Enter binary number: 101
In decimal: 5

Example 2:

Enter binary number: 11111
In decimal: 31

Solutions:


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

int main ()
{
    char a [9];
    printf ("Enter binary number: ");
    scanf ("%s", a);

    int length = strlen (a) - 1;

    int decimal = 0;
    for ( int i = length; i >= 0; i-- )
        decimal = decimal + (( a [i] - '0' ) * (int) pow ( 2, length - i ));

    printf ( "In decimal: %d\n", decimal );

    return 0;
}


About Tausiq
Studying B.Sc in CSE (Computer Science and Engineering) United International University, Dhaka, Bangladesh.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 48 other followers