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 Conversion
// 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);
}
Dave Sinkula 2,398 long time no c Team Colleague
prog-bman 4 Junior Poster
Dave Sinkula 2,398 long time no c Team Colleague
agentmulder 0 Newbie Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
bumsfeld 413 Nearly a Posting Virtuoso
041020 0 Newbie Poster
dilip.mathews 3 Junior Poster in Training
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
lester pinto 0 Newbie Poster
declum 0 Newbie Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
CSOL 0 Newbie Poster
krishna5687 0 Newbie Poster
taylorg 0 Newbie Poster
soorajshaji -3 Newbie Poster
soorajshaji -3 Newbie Poster
WaltP commented: What a piece ot crap! No formatting, conio.h, no comments. Terrible!! -3
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.