In this example, you will learn how to convert a binary number to a decimal using C language
C Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include<stdio.h> #include<stdlib.h> #include<math.h> unsigned long int power(unsigned long int x, int n) { if(n == 0) return 1; if(n == 1) return x; unsigned long int x2 = pow(x,n/2); if(n%2 == 0) return x2 * x2; return x2 * x2 * x; } int char_to_int(char d) { char str[2]; str[0] = d; str[1] = '\0'; return (int) strtol(str, NULL, 10); } unsigned int ConvertToBase10(int binary) { char snum[20]; // convert to String itoa(binary,snum,10); // how many characters? int nc = log10((int)binary)+1; int decimal = 0; for(int i = nc-1 ; i >= 0; i--) { decimal += char_to_int(snum[i]) * power( 2, (nc-1)-i); } return decimal; } int main() { int binary; while(1) { printf("Enter a binary number "); scanf("%d",&binary); printf ("%ld in base 2 =%ld in base 10\n",binary, ConvertToBase10(binary)); } return 0; } |
Output:
In this example,you have learned how to convert a binary number to a decimal using C language