binary to decimal conversion program, having probs

Discussion in 'Programmer's Corner' started by count_volta, Dec 15, 2010.

  1. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24
    Sorry forgot to say that this is programming in C.

    Hi, I'm doing some programming practice for fun and decided to write a simple program that converts binary to decimal based on the well known algorithm. For those who don't know for some reason, the algorithm is as follows:

    Say you want to convert 1101 to decimal.
    You do: 1*2^0 + 1*2^2 + 1*2^3 = 13

    Below is my code. The program runs but gives wrong answers. I don't understand why. I checked that the array contains the binary bits that the user enters. Then I use each element of the array as the bit location LSB to MSB, and loop through them to get the sum.

    Code ( (Unknown Language)):
    1. #include <stdlib.h>
    2. #include <stdio.h>
    3. #include <math.h>
    4. int main()
    5. {
    6. int a[32],n,i,j,m;
    7.     int sum =0;
    8.     double g = 2;
    9.    
    10. printf("Enter the number of bits in your binary number\n");
    11. scanf("%d",&n);
    12. printf("Enter the binary number with a space after every bit\n");
    13. for (i=0;i< n;i++);
    14. {
    15. scanf("%d",&a[i]);  // get binary number from user and enter it into array a
    16. }
    17.  
    18. for (j=0; j<n;j++);
    19.  
    20. {
    21.     if (a[j] == 1); // test if the bit is a 1, if so do 2^ bit index
    22.     {
    23.    
    24.     m =  pow(g, j);
    25.     sum = sum + m; // add all the 2^ bit indices for the bits that are 1 to get the decimal number
    26.         }
    27. }
    28.  
    29. printf("Your binary number in base 10 is %d\n", sum );
    30.  
    31. }[/i]
     
  2. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24
    I think the problem may have something to do with the double data type. According to my compiler, to use the pow function at least one of the arguments needs to be a double. I made the variable "g" a double and made it equal to 2. Until I did that, it didn't even compile.

    See below.

    [​IMG]
     
  3. debjit625

    Well-Known Member

    Apr 17, 2010
    790
    186
    simple ,cast it to double ... see how I did it

    Now their are problems in code logic and also in the way you used the language C so here is a simple way to do that i.e.. the way you wanted but their are better ways and faster algo anyway ,first never do this
    Code ( (Unknown Language)):
    1.  
    2. scanf("%d",&a[i]);  
    3. [/i]

    scanf's second parameter as per you will be an address of an int variable or a pointer to an int variable now the array is itself a pointer to the first element you cant pass its address...

    Something like this will work..
    Code ( (Unknown Language)):
    1.  
    2. [SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<stdlib.h>
    3. [/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<stdio.h>
    4. [/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<math.h>
    5. [/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] main()
    6. {
    7. [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]char[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] a[32] = {0};
    8. [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] n=0,i=0,j=0;
    9. [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] sum =0;
    10.  
    11. printf([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Enter the number of bits in your binary number\n"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]);
    12. scanf([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"%d"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2],&n);
    13. printf([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Enter the binary number\n"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]);
    14. scanf([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"%s"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2],a);
    15. [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]for[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] (j=(n-1);j>=0;j--)
    16. {
    17. [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]if[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2](a[j]== [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]'1'[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])
    18. {
    19. sum = sum + 1 * pow(2.0,([/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]double[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])(3-j));
    20. }
    21. [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]else
    22. [/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]{
    23. sum = sum + 0 * pow(2.0,([/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]double[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])(3-j));
    24. }
    25. }
    26. printf([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Your binary number in base 10 is %d\n"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2], sum );
    27. }
    28. [/SIZE]
    Another thing always initialize your variables.

    Good Luck
     
    count_volta likes this.
  4. debjit625

    Well-Known Member

    Apr 17, 2010
    790
    186
    One more thing ,always return value for your main function under a RTOS like windows ...
    Code ( (Unknown Language)):
    1.  
    2. int main(void)
    3. {
    4.  //All code goes here.............
    5.  return 0;
    6. }
    7.  
     
  5. thatoneguy

    AAC Fanatic!

    Feb 19, 2009
    6,357
    718
    strtol function

    Code ( (Unknown Language)):
    1.  
    2. printf("%d\n", strtol(b, "11010", 2));
    3.  
    I know it seems like cheating, but... :D
     
  6. septemberos

    New Member

    Dec 14, 2010
    5
    1


    The problem seems to be that you misunderstand syntax of conditional (if())and loop (for()) statements.

    In C you may have after if() and for() clause either a simple statement (terminated with ";") or a compouns statement (embraced with {} and without a ";" at the ent). C also allows empty statements (bare ";") and compound statements clocks ({}) without any loop or conditional.

    Your code:



    actually means:
    "for i to n DO NOTHING", then
    "get a SINGLE integer from stdin"

    Similar things occur with your next "for": if does NOTHING n times, then ONE time executes the compound statement. Inside that, you have the same problem with "if()" - if the condition is true it does NOTHING, then unconditionally executes

    Remember, at this point you have j == n. So that's what your output is - always 1 ^ n (number of bits), no matter what the bit values are.

    In order to get the behavior that you wanted, remove all ";"s after if() and for()s.

    BTW, when running the corrected program you may get a hint why "big endian" and "little endian" representations were invented.
     
    count_volta likes this.
  7. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24
    Thank you, I removed the semicolons after the if and for and it works. :D

    And yes you are right about the big and little endian. You have to enter the LSB first and MSB last because the loop accesses the LSB first. It looks backwards in the command console.

    So what exactly do the semicolons mean? Nobody really explained to me. They just say, after every statement, put them there. Does it specify the end of a statement?
     
  8. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24
    I actually modified the code so that you can enter the binary number, MSB first and LSB last.

    Code ( (Unknown Language)):
    1. #include <stdlib.h>
    2. #include <stdio.h>
    3. #include <math.h>
    4. int main()
    5. {
    6. int a[32],n,i,j,m;
    7.     int sum =0;
    8.     double g = 2;
    9.    
    10. printf("Enter the number of bits in your binary number: ");
    11. scanf("%d",&n);
    12. printf("Enter the binary number with a space after every bit:\n\n");
    13. [B]for (i=(n-1); i>=0; i--)[/B]
    14. {
    15. scanf("%d",&a[i]);  // get binary number from user and enter it into array a
    16. }
    17.  
    18. for (j=0; j<n;j++)
    19.  
    20. {
    21.     if (a[j] == 1) // test if the bit is a 1, if so do 2^ bit index
    22.     {
    23.    
    24.     m =  pow(g, j);
    25.     sum = sum + m; // add all the 2^ bit indices for the bits that are 1 to get the decimal number
    26.         }
    27. }
    28.  
    29. printf("Your binary number in base 10 is %d\n\n", sum );
    30.  
    31. return 0;
    32.  
    33.  
    34. }[/i]
    If anybody wants to use this program, go ahead. I just did this for fun. Now I'm going to write some code to go from decimal to binary.
     
    Last edited: Dec 16, 2010
  9. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24


    You are right, but then why does the program work? I removed the extra semicolons and it works. If the second argument of scanf is a pointer, and the array is a pointer to the first element, what is the problem?
     
  10. septemberos

    New Member

    Dec 14, 2010
    5
    1
    Semicolons don't have a definition in C which can be written in one sentence. A semicolon is used:
    1) To mark the end of a non-compound statement
    2) To mark the end of a declaration
    3) After while() in a do() statement (but not in a while() statement: a bare semicolon after while() in a while statement will have a meaning of "while [condition] do NOTHING"
    4) To separate three expressions in a for() statement

    Daniel
     
  11. septemberos

    New Member

    Dec 14, 2010
    5
    1


    With regard to scanf() behavior the OP's code was absolutely correct. In C "[]" operator has higher precedence than unary "&", so "&a" is equivalent to "&(a)" (address of a, which is an integer), and NOT "(&a)" as you seem to suggest.

    BTW, what's the meaning of "3-j" in your code?
     
  12. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24
    I am having another strange problem. I am using Visual C++ 2008 Express as my compiler. After I compile the program, and press "start without debugging", everything works fine. It converts my binary number and finishes with "press any key to continue".

    When I press "start debugging", all it does is ask for the number of bits in the binary number, then asks to enter the binary number, and when I enter it, the console window just closes without displaying the converted number and displaying the "press any key" message.

    I found my exe file and when I run it, the same thing happens, the window just closes. Did I not do something? I just started an empty project, and added my .cpp file as the source file in Visual C. Do I maybe need to add a header file or something. I never made an actual exe file before. Please help me out. Thanks.
     
  13. thatoneguy

    AAC Fanatic!

    Feb 19, 2009
    6,357
    718
    What is happening is the number is displaying, and the window is instantly closing, so you don't see it.

    Create a shortcut to cmd, and set the properties to not close on program completion. Or, hit <WinKey>+R, type 'cmd' and hit enter. It will pop up a command window, change directory to where your program is and run it, it will stay open and return to c:\whatever\your\path\is when finished.

    A better option is to modify the program:

    At the beginning, have the prompt be:
    "Input number of digits, or 'd' for converting decimal to binary, 'q' to quit"

    <get input>

    If it is a number, go through the routine above. If the input was not a number, then -> If the input was d, go to the decimal->binary routine, if it is q, then exit the program with return(0);

    Or you could have it go in an infinite loop with what you have, and use CTRL+C to stop the program, but that's a bit sloppy.

    Better yet is to create a form window to fill out and show results in, I'm used to X Win/*nix, but it isn't too hard with the visual dev tools.
     
    count_volta likes this.
  14. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24
    I wrote a little program to go the other way too. Decimal to binary. This one was more tricky and challenging, but I got it. I plan to have both programs in one, using a switch statement.

    I will post the exe here later if anyone can use such a program. I just did this for fun and programming practice. Here is the code.

    Code ( (Unknown Language)):
    1. #include <stdlib.h>
    2. #include <stdio.h>
    3. #include <math.h>
    4. int main()
    5. {
    6. int dec,i;
    7. int quotient;
    8. int remainder;
    9. int binary[32];
    10. int j;
    11.  
    12.  
    13.  
    14. printf("Please enter the decimal number which you want to convert to binary:\n");
    15. printf("\n");
    16. scanf("%d", &dec);
    17. printf("\n");
    18.  
    19. quotient = dec;
    20. printf("Your decimal number in binary is: ");
    21. i=0;
    22.  
    23. while (quotient != 0)  // while quotient is not zero, keep dividing by 2.
    24. {
    25.    
    26.     remainder = quotient % 2;
    27.     quotient = quotient / 2; // divide your decimal number by 2, and divide the answer by 2 and keep going until quotient is 0.
    28.    
    29.     if (remainder == 0 ) // if remainder is 0, the binary bit is 0
    30.  
    31.         binary[i] = 0;
    32.     else
    33.     {
    34.         binary[i] = 1;  // if remainder is 1, the binary bit is 1
    35.     }
    36.         i++;
    37.    
    38. }
    39.  
    40. if (dec != 0) // if your decimal number is not zero, print the array backwards, i.e. MSB to LSB
    41. {
    42. for (j=(i-1); j>=0; j--)
    43. {
    44. printf("%d", binary[j]);
    45. }
    46. printf("\n\n");
    47. }
    48. else  // if your decimal number is zero, so is your binary number.
    49. {
    50.     printf("0\n\n");
    51.  
    52. }
    53.  
    54. return 0;
    55.  
    56.  
    57. }[/i][/i]
     
    Last edited: Dec 18, 2010
  15. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24
    I have attached the completed program .exe to this post. This combines the two. It can do decimal to binary and binary to decimal.

    I have sent the exe to my friend who uses Windows 7 and he had errors when he tried to run it. It runs fine on my Windows XP.

    Can other people please try running it and tell me if it works. I wonder if I didn't add some necessary code or something. I never compiled an actual exe before.
     
  16. thatoneguy

    AAC Fanatic!

    Feb 19, 2009
    6,357
    718
    He may need to install the visual C runtime environment to get the .DLLs called by your compiled program.

    You can eliminate this need by compiling it as a "static" binary, but the resulting .exe file will be quite huge.
     
  17. count_volta

    Thread Starter Active Member

    Feb 4, 2009
    435
    24
    That is weird because the only libraries in my program are

    Code ( (Unknown Language)):
    1. #include <stdlib.h>
    2. #include <stdio.h>
    3. #include <math.h>
    I thought these libraries are default. What do people do when making a program that is supposed to run on Windows and make sure that the user has all the dependencies?
     
  18. thatoneguy

    AAC Fanatic!

    Feb 19, 2009
    6,357
    718
    Functions such as scanf, printf, etc. are all in the runtime library. The visual C runtime environment is usually installed with many other applications, so most everybody already have a few versions installed and they don't bump into the problem

    It's a free download from microsoft, you just need to get the correct version to match your compiler version. There are visual c and visual basic run time libraries for many versions, which makes it kind of a headache. Creating an .msi installer will include everything needed and set it up, you could do it in that method instead of sending the bare .exe file.
     
Loading...