Sneaker's Stub - The Grey Stuff!

Program To Convert Binary to Decimal Using C Language

**NOTE: The following code for “Program To Convert Binary to Decimal Using C Language” has been written and performed on Ubuntu OS, To run the following code in Windows on Turbo C, You need to add #include as one of the header files and getch() at the end of the code before main() closing brace “}”.

 

#include<stdio.h>
#include<math.h>
#include<string.h>
void main(){
int i,k=0,a=0,b=0;
char binnum[30];
printf("Enter a binary number: ");
gets(binnum);
a=strlen(binnum);
k=a;

for(i=0;i<a;i++){
	if(binnum[i]=='1'){	
	b=b+1*pow(2,k-1);
	}else{	b=b+0*pow(2,k); }
	k--;
}
printf("\nDecimal Equivalent for %s is %d\n",binnum,b);



}

 

Explanation For The Above Program:

  • Input a binary as a string
  • Store the length of the string in two different variables i.e ‘a’ for looping and ‘k’ for power of the base .
  • Run the loop from 0 to length – 1 or (i<a)
  • Read the string characters one by one and check if it is equal to ‘0’ or ‘1’
  • If the Character is equal to 1 then multiply the 1 by 2 to the power ‘k-1’ and store the sum in integer variable ‘b’
  • Print the resultant integer variable.

 

OUTPUT:

out3



Leave a Reply