The computer is a binary beast. We want to go from the one-fingered digital box to the ten-fingered human being and convert binary to denary(base 10) numbers. This is how it works, for instance, binary 10010 is calculated as 1*16+0*8+0*4+1*2+0*1 = decimal 18. Just because it's easy, let's throw in hexadecimal and octal results too. The added bonus is the almost foolproof entry of data.

```
// Binary to Decimal, Hexadecimal and Octal conversion program
// tested with Pelles C vegaseat 15dec2004
#include <stdio.h>
#include <string.h>
int bin2dec(char *bin);
int main()
{
char bin[80] = "";
char *p;
int dec;
while(strcmp(bin,"0"))
{
printf("\n Enter a binary number (just 0 to EXIT): ");
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 Hexadecimal = 0x%04X Octal = 0%o\n",dec,dec,dec);
}
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");
return (0);
}
for(b = 1, m = len; m > k; m--)
{
// 1 2 4 8 16 32 64 ... 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);
}
```

About the Author

Scientist

Dave Sinkula 2,398

Dave Sinkula 2,398

vegaseat 1,735

bumsfeld 413

vegaseat 1,735

vegaseat 1,735

vegaseat 1,735

soorajshaji -3

soorajshaji -3

WaltP
commented:
What a piece ot crap! No formatting, conio.h, no comments. Terrible!! -3