Problem with a binary to decimal conversion program. Help please.

This is a discussion on Problem with a binary to decimal conversion program. Help please. within the C++ Programming forums, part of the General Programming Boards category; So I tried debugging this program almost 10 times, each time finding a problem then making code to fix it, ...

  1. #1
    Registered User
    Join Date
    Jun 2013
    Posts
    17

    Problem with a binary to decimal conversion program. Help please.

    So I tried debugging this program almost 10 times, each time finding a problem then making code to fix it, I used to get wrong values but then now after I changed the calculation from an infinity while loop to a for loop (because after some changes I realized that now I know the number of entries, meaning the start and the end of the loop) the program now displays no values at all. I checked it thoroughly and until the calculation process its functioning exactly the way it should but then the calculation breaks hell loose . Also the for loop that raises 2 to the power needed works fine too so it must be something with the other processes included in the calculation. I would be grateful for any help I receive. Thank you.

    PS:This used to be a function of a multiple value types conversion program, I isolated it for easier analysis as a lone standing program.





    Code:
    #include<iostream>
    using namespace std;
    int main()
    {
    
    
        int d[10],e[10],anse=1,r,limit;
        short int counterd=0,i,j;
        float bind=0;
        cout<<"You can now enter the digits of your binary number. End the entry by entering -1"<<endl;
    
    
    
    
    
    
        while(1)                   //Entry stage 
        {
    
    
        cin>>d[counterd];
        if(d[counterd]==-1)
        {
            counterd--;        //This is because the counter used to count even the entry of -1
            break;
        }
    
    
        counterd++;
        }
        r=counterd;              //The counter value is copied to r so it decreases while counterd is the end of the for loop
        limit=r;                
        
        for(i=0;i<=counterd;i++)   //The digits is flipped so they start from the lowest instead of the highest in another array
        {
        
            e[i]=d[r];
            r--;
        }
    
    
                      
        for(i=0;i<=limit;i++) //The calculation happens here (mistakes too aparently)
        {    
        
    
    
        for(j=i;j>=0;i--)     //This raises 2 to the needed power according to it's position value(100th or 10th etc)
        anse*=2;
        
        
        bind+=e[i]*anse; //Multiplies it by the digits as required
        }
    
    
    
    
        
    
    
        cout<<bind;  //Decimal value answer
    
    
    
    
    return 0;
    }
    Last edited by Khalidkamalabdr; 07-25-2013 at 07:08 PM.

  2. #2
    Registered User
    Join Date
    Apr 2013
    Posts
    1,283
    You start with countered == 0, and then decrement it, making it negative. Why not store the bits as they are entered, with an increasing value of countered, so that the bits are stored most significant bit to least significant bit?

    You don't need to use a float for "bind" if you input less than 32 bits (assuming 32 bit signed integers).

    You don't need a double nested loop for the conversion. Use a single loop, start with anse == 1, and double it for each loop. There's an alternate method for the conversion, but get your program working first before looking at ways to optimize it.

  3. #3
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,699
    Well under normal circumstances, in binary, 1 represents some power of two that you then add to the number. You do not need to compute the power in its own loop; you will instead compute the power as you scan the input in that loop. The place value either counts or it does not.

    In pseudo code it is:
    Code:
    powerOfTwo = 1;
    for (i = 0; i < sizeOfInput; i++) {
      if (bits[i] == 1) {
        answer += powerOfTwo;
      }
      powerOfTwo *= 2; // preparation for next contributing place value
    }
    That's about all you need.

  4. #4
    Registered User
    Join Date
    Jun 2013
    Posts
    17
    To: Whiteflags

    Thank you. Your observations were really useful. Although I didn't understand why you think counterd would become negative on entry of a binary number of at least 1 digit. It's negative only if you simply enter only -1 as the input.
    But other than that they lead me to part of the solution and shorter code and yes you are right, I'm sure there is better ways of doing it but I wanted make a method of my own so I can get better in writing code and solving problems with code . Thank you again.

    To: rcgdlr

    Thank you for your help they lead to part of the solution! tried your suggestion but it didn't work, and after studying it I found out that I don't get why that code would do the job but also I think maybe I just didn't implement it right. Your other remarks and your code helped me develop this new code that does the job without fail though. Thank you again!


    The code below is the one that works ,after I'm done with the whole program value conversion I'm working on which this is a part of ,I will make it more readable and hopefully shorten it to maximize it's efficiency. Thank you both again .

    Code:
    #include<iostream>
    using namespace std;
    int main()
    {
     
     
        int d[10],e[10],anse=0,r,limit;
        short int counterd=0,i;
        int bind=0;
        cout<<"You can now enter the digits of your binary number. End the entry by entering -1"<<endl;
     
     
     
     
     
     
        while(1)                   //Entry stage 
        {
     
     
        cin>>d[counterd];
        if(d[counterd]==-1)
        {
            counterd--;        //This is because the counter used to count even the entry of -1
            break;
        }
     
     
        counterd++;
        }
    
    
    
    
    r=counterd;              //The counter value is copied to r so it decreases while counterd is the end of the for loop
    limit=r;                
         
        for(i=0;i<=counterd;i++)   //The digits is flipped so they start from the lowest instead of the highest in another array
        {
         
            e[i]=d[r];
            r--;
        }
     
     
                       
        for(i=0;i<=limit;i++) //The calculation happens here.
        {
            if(i==0)             
                anse+=1;   //First value will always be multiplied by 2^0 which is 1
            else
                anse*=2; //All the other values will keep increasing the power so this does exactly that
    
    
         
       
    
    
    
    
    
    
        bind+=e[i]*anse; //Multiplies it by the digits as required
        
     }
    
    
      cout<<bind;  //Decimal value answer
     
     
     
     
    return 0;
    }

  5. #5
    Registered User
    Join Date
    Apr 2013
    Posts
    1,283
    Quote Originally Posted by Khalidkamalabdr View Post
    To: rcgdlr ... countered ...
    Due to the way the indentation was done, I missed the part where you were incrementing countered, so you original code was OK. Also as explained by whiteflags, the conversion loop could be:

    Code:
    /* ... */
        anse = 1;
        for(i=0;i<=limit;i++)  //The calculation happens here.
        {
            bind += e[i]*anse; //Multiplies it by the digits as required
            anse *= 2;
        }

  6. #6
    Registered User
    Join Date
    Jun 2013
    Posts
    17
    Quote Originally Posted by rcgldr View Post
    Due to the way the indentation was done, I missed the part where you were incrementing countered, so you original code was OK. Also as explained by whiteflags, the conversion loop could be:

    Code:
    /* ... */
        anse = 1;
        for(i=0;i<=limit;i++)  //The calculation happens here.
        {
            bind += e[i]*anse; //Multiplies it by the digits as required
            anse *= 2;
        }
    I figured. I didn't indent the code properly at all,sorry! Ok NOW I get it,thanks a bunch !

  7. #7
    Registered User
    Join Date
    Apr 2013
    Posts
    1,283
    Another coding alternative using d[]:

    Code:
        bind = 0;
        for(i = 0; i <= countered; i++)
            bind = bind*2 + d[i];

  8. #8
    Registered User
    Join Date
    Jun 2013
    Posts
    17
    Quote Originally Posted by rcgldr View Post
    Another coding alternative using d[]:

    Code:
        bind = 0;
        for(i = 0; i <= countered; i++)
            bind = bind*2 + d[i];
    Hmmm. This seems to be calculating the values properly. Why did you use d[] though? Don't I still have to re-arrange the values?

  9. #9
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,699
    You can read binary from right to left or left to right, it doesn't make a difference until you start doing arithmetic. Thus any array with the input would work.

    Pretend d[10] contains 1,0,1. The algorithm is:

    0*2+1 = 1
    1*2+0 = 2
    2*2+1 = 5

    With d[10] you do have to be careful that the -1 doesn't count.

  10. #10
    Registered User
    Join Date
    Jun 2013
    Posts
    17
    Quote Originally Posted by whiteflags View Post
    You can read binary from right to left or left to right, it doesn't make a difference until you start doing arithmetic. Thus any array with the input would work.

    Pretend d[10] contains 1,0,1. The algorithm is:

    0*2+1 = 1
    1*2+0 = 2
    2*2+1 = 5

    With d[10] you do have to be careful that the -1 doesn't count.
    Hmmm,makes a lot of sense thank you. I'm going to have to schedule this code-shortening to another time though because in the mean time I'm working on the binary to hexadecimal conversion code. Be sure that your clever remarks will not be forgotten until then,thanks again. You have been very helpful to me . I have a question though about my new program, is there a short way of putting a number certain values for a variable as the condition for an if-statement? Not a range but certain values,that if either of them is found the condition is fulfilled by that I mean not all the values should be present but if just 1 is present the condition is true.
    Last edited by Khalidkamalabdr; 07-28-2013 at 11:34 AM.

  11. #11
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,699
    Long chains of OR will work:
    value == 1 || value == 2 || value == 3 || value == 5 || value == 8 ...
    Don't discount ways just because they are simple.

    You can always encapsulate such logic in a function and try other things, like:
    Code:
    int SanityCheck (int option)
    {
      static const int AllOptions[] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 };
      for (int i = 0; i < sizeof(AllOptions) / sizeof(AllOptions[0]); i++) {
        if (AllOptions[i] == option)
          return 1;
      }
      return 0;
    }
    Now you can use those two return values to discriminate from all the other numbers, and you know that for a 1 result the option is a value you want.

    You can also do something similar during input to discriminate from all possible input. It really depends on the situation.
    Last edited by whiteflags; 07-28-2013 at 12:26 PM.

  12. #12
    Registered User
    Join Date
    Jun 2013
    Posts
    17
    Quote Originally Posted by whiteflags View Post
    Long chains of OR will work:
    value == 1 || value == 2 || value == 3 || value == 5 || value == 8 ...
    Don't discount ways just because they are simple.

    You can always encapsulate such logic in a function and try other things, like:
    Code:
    int SanityCheck (int option)
    {
      static const int AllOptions[] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 };
      for (int i = 0; i < sizeof(options) / sizeof(options[0]); i++) {
        if (AllOptions[i] == option)
          return 1;
      }
      return 0;
    }
    Now you can use those two return values to discriminate from all the other numbers, and you know that for a 1 result the option is a value you want.

    You can also do something similar during input to discriminate from all possible input. It really depends on the situation.
    I never knew there was an "or" expression :S! Ok so instead of "&&" I can just use "||",that's pretty simple and will do just fine. Hmmm making a function to do the logic for me, I understand but I actually discarded that idea before settling on it having to be an if-statement because I want to include all the other calculations in the conversion function itself so I would spare the need of writing parameters for the new function but this function of yours,it's really interesting maybe I will practise similar functions afterwards so I can expand my little knowledge. Anyways thank you once again you helped me more than 3 times already!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Decimal to Binary conversion help
    By tru.cutru in forum C Programming
    Replies: 3
    Last Post: 07-08-2008, 10:17 PM
  2. binary decimal conversion
    By eerok in forum C Programming
    Replies: 2
    Last Post: 01-24-2006, 08:51 PM
  3. Decimal to Binary Conversion program
    By acidbeat311 in forum C Programming
    Replies: 5
    Last Post: 01-12-2006, 09:26 PM
  4. decimal to binary conversion
    By noob2c in forum C Programming
    Replies: 4
    Last Post: 05-29-2003, 08:07 PM
  5. Binary to decimal conversion help!
    By matrism in forum C Programming
    Replies: 4
    Last Post: 03-25-2002, 11:22 AM

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