954,479 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Binary to Decimal Conversion

0
By vegaseat on Dec 16th, 2004 1:47 pm

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);
}

test.c 11 error [Warning 603] Symbol 'bin' (line 8) not initialized
test.c 14 error [Warning 534] Ignoring return value of function 'gets(char *)'
test.c 14 error [Warning 421] Caution -- function 'gets(char *)' is considered dangerous
test.c 17 error [Info 725] Expected positive indentation from line 16
test.c 19 error [Warning 534] Ignoring return value of function '_fgetc(struct {...} *)'
test.c 29 error [Info 713] Loss of precision (assignment) (unsigned int to int)
test.c 47 error [Info 818] Pointer parameter 'bin' (line 24) could be declared as pointing to const

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 
prog-bman
Junior Poster
109 posts since Nov 2004
Reputation Points: 14
Solved Threads: 4
 

It was a linter, by the way.

scanf("%s",bin);

This is just a diguised version of gets(). It suffers the same ills.

". Written by some real winner named HAMMER."

...who apparently still knows more than you.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

what does n = (bin[k] - '0') do?

agentmulder
Newbie Poster
1 post since Apr 2005
Reputation Points: 10
Solved Threads: 0
 

like the comment says this turns for instance the character '1' to a numeric value 1

vegaseat
DaniWeb's Hypocrite
Moderator
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

Wow, dude your code makes it very clear!

bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 

please make this program in c..e.g cout,cin

041020
Newbie Poster
1 post since Oct 2005
Reputation Points: 10
Solved Threads: 0
 

A slight modification for the bin2dec function. Removes the nested for loop. Reduces the overhead and removes the temporary variable 'm'.

int bin2dec(char *bin)   
{
  int  b , k, n;
  int  len, sum = 0; 
 
  len = strlen(bin) - 1;
  for(k = 0; k <= len; k++) 
  {
   b = 1;
    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);
    }
     b = b<<(len-k);
    // sum it up
    sum = sum + n * b;
    //printf("%d*%d + ",n,b);  // uncomment to show the way this works
  }
  return(sum);
}
dilip.mathews
Junior Poster in Training
89 posts since Jun 2006
Reputation Points: 16
Solved Threads: 3
 

A nice improvement by dilip.mathews! Thanks!

vegaseat
DaniWeb's Hypocrite
Moderator
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

Nice program!!!

i'm favorly new to C and was wondering how the
line b<<(len-k) worked... all i know its shifts the digits to the left..
but what i dont get is by how much..

....ie. bin<<1 =multiply it by 2 so what does len-k do in the above statement..

hope that doesnt' sound confusing..

and also what does teh sum stand for in "sum=sum+n*b"

cheers

lester pinto
Newbie Poster
1 post since Aug 2006
Reputation Points: 10
Solved Threads: 0
 

your code is much long.. i found one in net
try it

long bin2dec(char *s)
{
   long r=0;
   for (; *s; r = (r<<1) | (*s++ - '0'));
   return r;
 }
declum
Newbie Poster
4 posts since Feb 2006
Reputation Points: 10
Solved Threads: 0
 

Good for you, but shorter is not always better. There is no error trapping, or explanation/comment how it works!

vegaseat
DaniWeb's Hypocrite
Moderator
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

binary 10010 is calculated as 1*16+0*8+0*4+1*2+0*1 = decimal 18
hence b = b<<(len-k) does the multiplication by 1,2,4,8,16 ...

sum = sum + n * b;
// this will explain it ...
printf("%d*%d + ",n,b);

vegaseat
DaniWeb's Hypocrite
Moderator
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 
/*conversion of binary number to decimal*/
#include <stdio.h>

int main()
{
	int binary, digit, base = 0, decimal = 0;
	printf("enter a binary number: ");
	scanf("%d", &binary);
	printf("Entered binary number is: %d\n", binary);
	while(binary)
	{
		digit = binary % 10;
		decimal += digit << base;
		base += 1;
		binary /= 10;
	}
	printf("decimal equivalent of the entered binary number is: %d", decimal);
	return 0;
}
CSOL
Newbie Poster
1 post since Nov 2009
Reputation Points: 10
Solved Threads: 0
 

//decimal to binary

#include<stdio.h>
void main()

{

	long int deci,rem,bin,p=1;
	printf("enter no");
	scanf("%ld",&deci);
	if (deci > 0)

	{
		while (deci > 0)

		 {
			rem=deci%2;
			bin=rem*p+bin;
			p=p*10;
			deci=deci%2;

			}
			printf("binary no is %ld",bin);
				//end of while loop

			getchar();

			}

			//end of condition

			else

				printf("binary no for +tive integer only");

				getchar();


				}
krishna5687
Newbie Poster
1 post since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

Nice code everyone! It's funny - I just had to do the same thing for a class the other day in school.

I uploaded the code to my blog... here it is:

Also here:

int bin2dec(char * binstr)
{
int dec = 0;
int len = strlen(binstr);
int i = 0;

while(i < len)
{
dec = (dec << 1) + (binstr[i] - 0x30);
i++;
}
return dec;
}


That's my bin2dec function. I wrote a full explanation about it on my site (or at least tried :P) Good to compare with the others.

taylorg
Newbie Poster
3 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: