Monday, 13 March 2017
On 21:56 by Vardan Kumar in C tutorial 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
- 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.
- Next for every 1 in our array we'll add the previous addition with 2 to the power,position of that element in array,
- 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.
- Now sum=1*2^0=1 in iteration.(1 at index 0)
- Again for next 1 we will have sum=1+2^2=5.(1 at index 2)
- Again for next 1 we will have sum=5+2^3=13(1 at index 3)
- Since there is no 1 there after hence we have 13 as our binary equivalent for the given input.
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.
Also Read 8-Bit Decimal to Binary Conversion
Subscribe to:
Post Comments (Atom)
Search
Popular Posts
-
Troubleshooting Cisco VPN client Before starting troubleshooting, Let us see what VPN is and what it requires to perform its intended f...
-
Evolution-Mobile Phones With the development of portable technology,wireless communication has so evolved that (According to the announce...
-
File Versioning C# File versioning, saving file with unique file name in c# File versioning allows a user to have several versions of ...
-
Text Box Hint in c# Windows Form Application Text Box Hint in c# Windows Form Application While developing a windows form applicat...
-
Unable to set the Freeze Panes property of Window Class C# It is generally easy to resolve the compile time errors because the reason fo...
0 comments:
Post a Comment