C Program to convert Binary Number into Decimal Number

In this blog, we will discuss the conversion of the given binary number into a decimal number. For example, the decimal equivalent of binary number 1010 is 10 which can be depicted as follows: Binary to Decimal
Consider the binary number from the last.
For the above mentioned example,

0 * 2^0 = 0
1 * 2^1 = 2
0 * 2^2 = 0
1 * 2^3 = 8

Decimal number = 0 + 2 + 0 + 8 = 10 Algorithm: Input the binary number Multiply each digit of the binary number with the power of 2 and add each multiplication result The power starts from 0 to n-1 where n is the total number of digits in the binary number Implementation using C: #include<stdio.h>
#include<math.h>

int convert(long int n)
{
int decimal = 0, i = 0, remainder;
while(n!=0)
{
remainder = n%10;
n = n/10;
decimal = decimal + remainder*pow(2,i);
i++;
}
return decimal;
}

int main()
{
long int n;
printf("Enter a binary number: ");
scanf("%ld",&n);
printf("\n Decimal number : %d \n",convert(n));
return 0;
} Output:
Enter a binary number : 1010
Decimal number : 10 Happy Coding! Follow us on Instagram @programmersdoor Join us on Telegram @programmersdoor Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem. Follow Programmers Door for more. #blog #interview #placement #learn #computer #science

        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door