How to convert binary number to decimal in C

1 Answer

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

int binary_to_decimal(char s[]) { 
    int dec = 0;
  
    for (int i = strlen(s) - 1, j = 0; i >= 0; i--, j++) { 
        if (s[i] == '1') {
            dec += pow(2, j); 
        }
    } 
    return dec; 
} 
    
int main() 
{ 
    char s[] = "10101011";  
  
    printf("%i\n", binary_to_decimal(s));
	
	return 0;
} 
  
  
/*
run:
    
171 

*/

 



answered May 9, 2019 by avibootz

Related questions

1 answer 224 views
2 answers 210 views
1 answer 174 views
1 answer 110 views
110 views asked Aug 24, 2021 by avibootz
2 answers 285 views
285 views asked Sep 9, 2014 by avibootz
1 answer 140 views
1 answer 141 views
...