hey,
i made this a few years ago. i want to take the error when u enter a different number and would like to make it more compact. can you guys help me make it smaller. this is a 8 bit binary to decimal converter.

``````#include <stdio.h>
#include <string.h>

int bin2dec(char *bin);

int main()

{

char bin[9] = "";

char *p;

int dec;

while(strcmp(bin,"0"))

{

printf("\n Enter a binary number (just 0 to EXIT): ");  //Enter number to be converted in binary form

fgets(bin, sizeof(bin), stdin);

// check for and remove trailing \n

if ((p = strchr(bin,'\n')) != NULL)

{

*p = '\0';

}

dec = bin2dec(bin);

if (dec) printf("\nDecimal = %d \n",dec); //Display Converted # in Decimal,

}

getchar(); // wait

return 0;

}

// convert a binary string to a decimal number, returns decimal value

int bin2dec(char *bin)

{

int b, k, m, n;

int len, sum = 0;

len = strlen(bin) - 1;

for(k = 0; k <= len; k++)

{

n = (bin[k] - '0'); // char to numeric value

if ((n > 1) || (n < 0))

{

puts("\n\n ERROR! BINARY has only 1 and 0!\n"); //Error if anything other than 1 or 0 entered

return (0);

}

for(b = 1, m = len; m > k; m--)

{

// 1 2 4 8 16 32 64 128 ... place-values, reversed here

b *= 2;	//

}

// sum it up

sum = sum + n * b;

//printf("%d*%d + ",n,b); // uncomment to show the way this works

}

return(sum);

}``````
Salem commented: I see you've still to figure out code tags - have a cookie for your unreadable mess. -5

## All 3 Replies

``````for(b = 1, m = len; m > k; m--)
{
// 1 2 4 8 16 32 64 128 ... place-values, reversed here
b *= 2;
}
// sum it up
sum = sum + n * b;``````

Include <math.h>
and replace your the previously mentioned code with this:

``sum += n * (int)pow(2, k);``

> and replace your the previously mentioned code with this:
> sum += n * (int)pow(2, k);
a) it's slower
b) you're at the mercy of whatever inaccuracies are inherent in the floating point library.

> can you guys help me make it smaller.
Sure
a) use code tags - something you're consistently failing to do
b) strip out the excess of newlines
c) learn to indent code.
It's horrible.

Well, if you're not afraid of pointers...

``````int bin2dec(char * bin)
{
int n;
int sum = 0;
while (*bin)
{
n = *bin - '0';
if (n < 0 || n > 1)
{
printf("\nInvalid binary character: '%c'\n", *bin);
puts("Binary only uses the digits 0 and 1.\n");
return 0;
}
// double what we had before and add a new low bit
sum = (sum << 1) + n;
++bin;
}
return sum;
}``````

I'm really hoping this wasn't homework, you might be hard-pressed to explain where the idea came from :)

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.