A Program to Convert Binary to Decimal

In this example, we are giving a program to convert a number from binary to decimal.


Program to convert binary to decimal:

  1. #include <math.h>
  2. #include <stdio.h>
  3. int convert(long long n);
  4. int main() {
  5. long long n;
  6. printf("Enter a binary number: ");
  7. scanf("%lld", &n);
  8. printf("%lld in binary = %d in decimal", n, convert(n));
  9. return 0;
  10. }
  11. int convert(long long n) {
  12. int dec = 0, i = 0, rem;
  13. while (n != 0) {
  14. rem = n % 10;
  15. n /= 10;
  16. dec += rem * pow(2, i);
  17. ++i;
  18. }
  19. return dec;
  20. }

Output:

Enter a binary number: 11011
11011 in binary = 27 in decimal