Can anyone help me with my code?!

I need to do a programm binary to decimal converter without using library, just stdio.h

my code works wrong

void bin2dec(){

long int n;  
int s=1,j,p=1,i=0,x;
int digit=1;


printf("Input a binary number: ");  
scanf("%ld",&n);  
while(digit==1)  
{  
x=n%10;  
s=s+pow(2,i);
i=i+1;  
n=n/10; 


if(n==0)
	digit=0;  
}  
printf("\nDecimal equivalent = %d",s);  
 
  for(j=1;j<=i;j++) 
	p = p*2;	  

}

And this is a power function

int pow(int b,int z){
	int result=1;
	while (z>0) {
		result=result*b;
		z--;
	}
	return result;
}

what's wrong???

Recommended Answers

All 4 Replies

Can anyone help me with my code?!

I need to do a programm binary to decimal converter without using library, just stdio.h

my code works wrong

It does? Think it might be helpful to explain what it does wrong?

Well I implemented your code, and cam up with this. If you dont understand anything in it, feel free to ask.

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

int bin2dec(int num, int *result)
{
    int i=0,x;

    while(num>0)        //does better job than using an if as you did
    {
        x=num%10;
        if(x==1)
        {
            *result=*result+pow(2,i);       //no need to make any function pow as pow is built in math.h
        }
        else if(x > 1)                      //this ways it wont except 2
        {
            printf("Wrong Input!\n");
            return 1;
        }
    i++;
    num/=10;
    }
}


void main()
{
    long int n, result;
    result = 0;
    int i;

    printf("Input a binary number: ");
    scanf("%ld",&n);

    i = bin2dec(n, &result);
    if (i==1)
    {
        return 0;
    }
    printf("\nDecimal equivalent = %d",result);
}

I you want to convert binary to decimal then you can use calculator. To get this calculator click Here

The proposed solutions are limited to integers on the input, about making the maximum input value approximately 1111111111, which (interpeted in binary) is 1023.
As homework, that would be a "C" grade.
A better solution would be to read the input as a string, accepting up to 32 characters, where each character is a '1' or a '0'.

Once you have the string, process the MSB first, and multiply the result each time by 2. Using an insigned integer will allow the full range 0 to (~0).

unsigned int result = 0;
char *p - inputString;
/* .. Remove leading spaces here */

while (*p == '0' || *p == '1') {
    result *= 2;
    result += (*p - '0');
    p++;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.