program to convert a binary number to a decimal number.
Program to convert a binary to decimal number.
#include <stdio.h>
int main()
{
int n, sn, i = 1, dec = 0, rem;
printf("Enter a binary number:\t");
scanf("%d", &n);
sn = n;
while (n > 0) /* work when number is
greater than 0.*/
{
rem = n % 10; // reminder is 0 or 1 only
if (rem == 1 || rem == 0) //binary number
{
dec = dec + rem * i;
i *= 2; // power of 2's.
n = n / 10;
}
}
printf("Decimal Equivalent of %d is %d ", sn, dec);
return 0;
}
Output :
Enter a binary number: 1101
Decimal Equivalent of 1101 is 13
for this we extract binary digits from right and add them after multiplying power of 2.
Comments
Post a Comment