How to convert binary number to decimal number in C

2 Answers

0 votes
#include <stdio.h> 
#include <math.h> 

long BinaryToDecimal(long n);

int main(void)
{   
    long binary;
    
    printf("Enter a binary number: ");
    scanf("%ld", &binary);
    printf("The decimal number of %ld is %ld\n", binary, BinaryToDecimal(binary));
     
    return 0;
}
 
long BinaryToDecimal(long n) 
{
    int remainder; 
    long decimal = 0, i = 0;
    
    while (n != 0) 
    {
        remainder = n % 10;
        n = n / 10;
        decimal = decimal + (remainder * pow(2,i));
        i++;
    }

    return decimal;
}

 
/*
run:
   
Enter a binary number: 11101111
The decimal number of 11101111 is 239

*/

 



answered Oct 27, 2016 by avibootz
edited Jun 10, 2017 by avibootz
0 votes
#include <stdio.h> 
#include <math.h> 
 
long BinaryToDecimal(long binary);
 
int main(void)
{   
    long binary = 11101111;
     
    printf("The decimal number of %ld is %ld\n", binary, BinaryToDecimal(binary));
      
    return 0;
}
  
long BinaryToDecimal(long binary) 
{
    int decimal = 0, i = 0;
 
    while (binary != 0)
    {
        decimal += (binary % 10) * pow(2, i);
        i++;
        binary /= 10;
    }
    
    return decimal;
}
 
  
/*
run:
    
The decimal number of 11101111 is 239
 
*/

 



answered Jun 10, 2017 by avibootz

Related questions

1 answer 230 views
1 answer 201 views
1 answer 185 views
1 answer 115 views
115 views asked Aug 24, 2021 by avibootz
2 answers 292 views
292 views asked Sep 9, 2014 by avibootz
1 answer 148 views
1 answer 147 views
...