// BINARY to DECIMAL
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
int n=0,POWER=0,i,j;
char ar1[20];
char ar2[2] = {'0','1'}; //ar2[0]=0, ar2[1]=1
printf("Enter any Binary Number : ");
scanf("%s",&ar1);
for(i=strlen(ar1)-1;i>=0;i--)
//let entered number = 1011, then i=4-1=3;i>=0;i--
//it means i=3,2,1,0
{
for(j=0;j<2;j++)
//j=0,1
{
if(ar1[i]==ar2[j])
{
n=n+j*pow(2,POWER);
}
}
POWER++;
/*
in first step
ar1[3]=1,ar2[0]=0 and ar2[1]=1
therefore ar1[3]=ar2[1]
it means n = 0+1*pow(2,POWER)= 0+1*pow(2,0) = 0+1*1 = 1
in second step
ar1[2]=1,ar2[0]=0 and ar2[1]=1
therefore ar1[2]=ar2[1]
it means n = 1+1*pow(2,POWER)= 1+1*pow(2,1) = 1+1*2 = 3
in third step
ar1[1]=0,ar2[0]=0 and ar2[1]=1
therefore ar1[1]=ar2[0]
it means n = 3+0*pow(2,POWER)= 3+0*pow(2,2) = 3+0*4 = 3
in fourth step
ar1[0]=1,ar2[0]=0 and ar2[1]=1
therefore ar1[0]=ar2[1]
it means n = 3+1*pow(2,POWER)= 3+1*pow(2,3) = 3+1*8 = 11
now n = 11
*/
}
printf("Decimal Number = %d",n);
}
//Another Method
//Binary to Decimal
#include <stdio.h>
int main()
{
int n,dec=0,temp=1,REM;
printf("Enter any Binary Number : ");
scanf("%d",&n);
while(n>0)
{
REM = n%10;
dec = dec + REM*temp;
n = n/10;
temp = temp*2;
}
/*
let n = 11101
step 1:
11101>0 true
REM = 11101%10 = 1
dec = 0 + 1*1 = 0 + 1 = 1
n = 11101/10 = 1110
temp = 1*2 = 2
step 2:
1110>0 true
REM = 1110%10 = 0
dec = 1 + 0*2 = 1 + 0 = 1
n = 1110/10 = 111
temp = 2*2 = 4
step 3:
111>0 true
REM = 111%10 = 1
dec = 1 + 1*4 = 1 + 4 = 5
n = 111/10 = 11
temp = 4*2 = 8
step 4:
11>0 true
REM = 11%10 = 1
dec = 5 + 1*8 = 5 + 8 = 13
n = 11/10 = 1
temp = 8*2 = 16
step 4:
1>0 true
REM = 1%10 = 1
dec = 13 + 1*16 = 13 + 16 = 29
n = 1/10 = 0
temp = 16*2 = 32
step 5:
0>0 false
*/
printf("Decimal Number : %d",dec);
return 0;
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.