C program to convert binary into decimal.

 

01  #include<stdio.h>
02
03 long bin2dec(char binaryString[]);
04
05 int main()
06 {
07 char bstr[20];
08 long decNum;
09
10 printf("Enter binary string (0-1) : ");
11 gets(bstr);
12
13 decNum=bin2dec(bstr);
14
15 if(decNum==-1)
16 {
17 printf("Invalid string.");
18 }
19 else
20 {
21 printf("Decimal number : %ld",decNum);
22 }
23
24 return 0;
25 }
26
27 long bin2dec(char binaryString[])
28 {
29 long dnum=0;
30 int i=0;
31 int n;
32
33 while(binaryString[i]!='')
34 {
35 n=binaryString[i]-48; /* convert char '0' or '1' into integer 0 or 1 */
36
37 /*check for 0 and 1 */
38
39 if(n!=0 && n!=1)
40 return -1; // invalid string
41
42 dnum=(dnum*2)+n;
43 i++;
44 }
45
46 return(dnum);
47
48 }
 
 
 
 
OUTPUT :

Enter binary string (0-1) : 110011
Decimal number : 51

Related Post

Leave a Reply

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