I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » C/C++ »

what am i doing wrong here

browngod2002\′s Photo
25 Sep 06, 5:37PM
(4 replies)
what am i doing wrong here
This is supposed to return the decimal form of the binary number entered. #include "stdafx.h" #include <stdio.h> #include <math.h>

/*function prototype*/ int btod(int number);

int main(int argc, char* argv[]) { unsigned int number;

printf("Enter an interger(0's and 1's): "); scanf("%d", &number);

printf("The decimal equilavent is %d
", btod(number));

getchar(); getchar(); return 0; }

int btod(int number) { int power = 1; int total = 0;

while (number > 0) { total += number % 10 * power; number = number / 10; power = power * 2; }

return number; }

lucian\′s Photo
26 Sep 06, 7:55PM
In function "btod" at the end of your listing, you should have:

<div class="orangebox">[code]</div>

instead of

<div class="orangebox">[code]</div>

Also you don't really need to include "stdafx.h". Apart from this, your algorithm should work well on all cases.

lucian\′s Photo
26 Sep 06, 8:25PM
However I would like to suggest another method of computing the decimal equivalent of a binary number, which has several advantages. Here is the code:

#include &lt;stdio.h&gt;
#include &lt;conio.h&gt;
 
int main&#40;&#41;
&#123;
  printf&#40;&quot;Input binary value&#58;\n&quot;&#41;;
 
  char c;
  double value = 0;
  while &#40;&#40;c = getch&#40;&#41;&#41; != 13&#41;
  &#123;
    printf&#40;&quot;%c&quot;, c&#41;;
    value = value*2.0 + c - '0';
  &#125;
  printf&#40;&quot;\nCorresponding decimal value&#58;\n%.0lf\n&quot;, value&#41;;
 
  return 0;
&#125;

It has the advantage that you can convert larger binary values into decimal form, since you are not storing the binary number as an integer, rather you keep each digit the user inputs in a char variable. Also the result is stored inside a variable of type double to permit conversion of very large numbers.

Try inputting

100101010000001011111001000000000

you should get a decimal value of 5000000000, which is higher than the maximum unsigned long int number.

browngod2002\′s Photo
26 Sep 06, 9:25PM
thank both of you. I feel so stupid cause I was returning the wrong value. The simple things in creating code can cause you big headaches. Thank you again
lucian\′s Photo
27 Sep 06, 7:20AM
I am glad I could help. It's true one needs to focus a lot while programming, the compiler cannot always guess what you are trying to do. If you encounter any other problems, please post a new topic and I will send you a reply as soon as possible. Of course only if I could handle the problem. :)
Currently you need to be logged in to leave a message.