C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 02-09-2010, 02:15 PM   #1
Registered User
 
Join Date: Feb 2010
Posts: 1
Help

I am writing a program that will convert a binary number that a user enter into decimal. The code works but when I the I enter a number like 1111 it come up to 16.

Here is the coding:
Code:
#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
int sum=0;
int power=1;
int binary;


printf("Enter a binary number:");/* user enter a binary number*/
scanf("%d",&binary);

while (binary>0)
{
sum=sum+
binary%10*power;
binary=binary/10;
power=power+2;
}
printf("The decimal equivalent: %d\n",sum);

return 0;
}
Thanks for your help
Reply With Quote
lexy is offline   Reply With Quote
Old 02-09-2010, 02:34 PM   #2
Unregistered User
 
Yarin's Avatar
 
Join Date: Jul 2007
Posts: 981
This is because your input buffer is an int, you should be using a string instead, and parse it.
__________________
May the Source be with you.
Yarin is offline   Reply With Quote
Old 02-09-2010, 02:38 PM   #3
Registered User
 
jeffcobb's Avatar
 
Join Date: Dec 2009
Location: Henderson, NV
Posts: 532
Wow. Another way would be to read the binary number as a string, the iterating through the character array (right to left) add 1,2,4,8,16, etc to the sum then spit out the sum. But your way is probably closer to what your teacher wants.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
   int nRC = 0;
   int nCurVal = 1;
   int sum = 0;
   char inputArray[9];
   memset(inputArray,0,9);
   scanf("%s", inputArray);
   // now walk the array:
   int nPos = strlen(inputArray)-1;
   while(nPos >= 0)
   {
      if( inputArray[nPos] == '1')
      {
	 sum += nCurVal;
      }
      --nPos;
      nCurVal *= 2;
   }
   printf( "%s converted to decimal is %d\n", inputArray, sum);

   return nRC;
}
__________________
C/C++ Environment: GNU CC/Emacs
Make system: CMake
Debuggers: Valgrind/GDB
jeffcobb is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump


All times are GMT -6. The time now is 09:21 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22