Never underestimate the power of Passion!

Monday 13 March 2017

On 21:56 by Vardan Kumar in    No comments

Binary to Decimal Conversion


Sometimes in a program, the output is in the form of binary number system. Such output is really comfortable for a computing machine to understand but user can not understand such kind of output form i.e. binary output, hence if our program is generating a binary output a functional logic should be written in order to convert that binary to decimal number system.

Logic

  1. We'll take the input as an array or if we want to take the input directly as an integer then we have to separate the digits of that integer and store the same in an array in reverse order since we are to perform calculations bit by bit. Suppose we enter 0 0 0 0 1 1 0 1.
  2. Next for every 1 in our array we'll add the previous addition with 2 to the power,position of that element in array,
  3. Since we will store the values in array in reverse order hence 0th index will be 1 followed by 0 at 1st index and so on, giving our array in sequence as 1 0 1 1 0 0 0 0.
  4. Now sum=1*2^0=1 in iteration.(1 at index 0)
  5. Again for next 1 we will have sum=1+2^2=5.(1 at index 2)
  6. Again for next 1 we will have sum=5+2^3=13(1 at index 3)
  7. Since there is no 1 there after hence we have 13 as our binary equivalent for the given input.

8-Bit Binary to Decimal Conversion in C
Output Binary to Decimal



Source Code

#include<Stdio.h>
#include<math.h>

int Binary2Decimal(int aBin[]){
    int sum = 0, i;
    for(i = 0; i < 8; i++){
        if(aBin[i]) 
            sum += pow(2,i);
    }
    return sum;
}

void main()
{
    int iBin[8],i,cDec;
    printf("Please enter 8 bit binary integer bit by bit\n");
    for(i=7;i>=0;i--)
    {
        scanf("%d",&iBin[i]);
    }
    cDec=Binary2Decimal(iBin);
    printf("The equivalent decimal is %d",cDec);
}


 If n bit conversion is required use of macros is recommended in order to write a generic program for the same, logic will be same.

0 comments:

Post a Comment