• support@answerspoint.com

How to convert Binary to Decimal in C Program?

551

I have a simple code to convert binary to decimal numbers. In my compiler, the decomposition works just fine for number less than 1000, beyond the output is always the same 1023. Anybody has an idea ?

  • C++

  • asked 2 years ago
  • Prabhat Dey

2Answer


0

C code for binary to decimal conversion:

#include<stdio.h>
 
int main(){
   
    long int binaryNumber,decimalNumber=0,j=1,remainder;
 
    printf("Enter any number any binary number: ");
    scanf("%ld",&binaryNumber);
 
    while(binaryNumber!=0){
         remainder=binaryNumber%10;
        decimalNumber=decimalNumber+remainder*j;
        j=j*2;
        binaryNumber=binaryNumber/10;
    }
 
    printf("Equivalent decimal value: %ld",decimalNumber);
 
    return 0;
}
 
 
Sample output:
 
Enter any number any binary number: 1101
Equivalent decimal value: 13
  • answered 2 years ago
  • G John

0

try this :

#include <stdio.h>
int main(void) 
{ 
char bin; int dec = 0;

while (bin != '\n') { 
scanf("%c",&bin); 
if (bin == '1') dec = dec * 2 + 1; 
else if (bin == '0') dec *= 2; } 

printf("%d\n", dec); 

return 0;

}
  • answered 2 years ago
  • B Butts

Your Answer

    Facebook Share