-1

I have created a binary to decimal converter but even small numbers written in binary have many digits and thus are too large to be held by an integer variable on a 16 bit machine. Is there any way around this. The program is in C. Here is the code, thanks:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

void main()
{
 clrscr();
 int a,b,d=0,x=1;
 int check(int y);
 printf("Enter your number in Binary:");
 scanf("%d",&a);
 if(check(a)==0)
 {
  printf("Number tolerable. Conversion Process Initiated.");
 }
 else 
 {
  printf("Number not binary. Try again.");
  exit(1);
 }

 while(a!=0)
 {
   if(a%10==1)
    {
     d=d+x;
    }
   a=a/10;
   x=x*2;
 }
 printf("\nDecimal:%d",d);
 getch();
}

int check(int y)
{
  while(y!=0)
  {
   if(y%10!=0&&y%10!=1)
   {
    return 1;
   }
   else
   {
    y=y/10;
   }
  }
 return 0;
}
alk
  • 69,737
  • 10
  • 105
  • 255

3 Answers3

2

A simple way would be to store binary number into a character array.And to convert it into number see following steps-

1.Loop starting from i=n-1 to i>=0 ( array of size n).

2.Check if character at index i is 0 or 1.

Recognize 0 and 1 as follows-

3.If 0 then digit is 0.

4.If 1 then digit will be equal to 2^i (i being the index).

5.Last step would be add them.

Else use an integer array.

ameyCU
  • 16,489
  • 2
  • 26
  • 41
0

The %d format specifier to scanf expects a number to be entered in decimal format. There is no binary format specifier, so you have to read in the number as a string and parse through it.

For example, if the user enters "101011", you need to recognize this as 2^5 + 2^3 + 2^1 + 2^0 and add those value to the resulting number (to be clear, I'm using ^ to denote exponentiation instead of bitwise xor).

dbush
  • 205,898
  • 23
  • 218
  • 273
0

there's no real need to store the binary digits.

#include <string.h>

int n=0,c;
printf("Enter your number in Binary:");
while(strchr("01",c=getch()))
    n+=n+c-'0';
Jasen
  • 11,837
  • 2
  • 30
  • 48