Decimal to Binary

This is a discussion on Decimal to Binary within the C++ Programming forums, part of the General Programming Boards category; Im writing this converter and i dont see why the first time it gives me the right result but after ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    795

    Decimal to Binary

    Im writing this converter and i dont see why the first time it gives me the right result
    but after it gives me one 0 less every time.

    EX. First time 8 --> 1000
    After 8 --> 100

    Code:
    #include <iostream>
    using namespace std;
    #include <cstring>
    #include <cstdlib>
    
    int number, total, binary[8];
    void prog();
    
    int main()
    {
          prog();
          return 0;
    }
    
    void prog()
    {
       cout<<"Enter decimal to convert: ";
       cin>>number;
        while(number>0)
        {
             if((number%2)==0)
             {
                binary[total] = 0;
                number = number/2;
                total++; /* increasing by one each time will yield the
                            number of numbers in the array. */
             }
             else
             {
                binary[total] = 1;
                number = number/2;
                total++;
             }
        }
       
        total--; 
        
        while(total>=0)
        {
             cout<<binary[total];
             total--;
        }
    
       cout<<endl<<endl;
       prog();
    }
    Compiler MSVC++ 2013 with Code::Blocks.

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    Instead of looping with recursion:
    Code:
    void foo()
    {
        // do stuff
        foo();  
    }
    loop with a real loop:
    Code:
    void foo()
    {
        while(1)
        {
            // do stuff
        }
    }
    This way you don't run out of stack space.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    Also, you need to initialize the total variable each time through the loop. This will likely fix your problem.

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    795
    Thank you Bithub!

    I changed both things you said. Initializing 'total' solved the problem.

    I thought it was set back to zero each time in this loop. Apparently not.

    Code:
    if((number%2)==0)
             {
                binary[total] = 0;
                etc...
    Here it assigns 0 to the first element of binary[].
    Last edited by Ducky; 04-21-2009 at 11:45 AM.
    Compiler MSVC++ 2013 with Code::Blocks.

  5. #5
    Registered User
    Join Date
    Nov 2002
    Posts
    319
    your incrementing total and thats not set to 0 so its undefined value to start with

  6. #6
    Registered User
    Join Date
    Dec 2007
    Posts
    795
    The first element of binary[total] is set to zero.
    I tested it.
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        int binary[8], total=0;
        binary[total] = 3;
    
        for(int total = 0; total < 8; total++)
        cout << binary[total] <<endl;
    
    return 0;
    }
    Compiler MSVC++ 2013 with Code::Blocks.

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Umm, that program doesn't set the first element of binary[] to zero. Here's what it does:
    • Allocate an array of 8 ints called binary, which are initialized to "random" values.
    • Allocate a new int called total, which is initialized to zero.
    • Set binary[total] to 3 -- i.e., set binary[0] or rather the first element in the array binary[] to 3. The remaining elements are uninitialized.
    • Print out the elements of binary[]. You'll probably find that the first number is 3 and the other numbers seem pretty random.


    Here was my output. (This is a system with 64-bit ints, so the numbers may have a larger range than your output.)
    Code:
    $ g++ init0.cpp -o init0
    $ ./init0
    3
    5472000
    0
    -1079852504
    134514489
    10885717
    6133204
    -1079852520
    $
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    Registered User
    Join Date
    Dec 2007
    Posts
    795
    Initialized to 0 or 3 doesnt make a difference. It was just an example.

    My point was that its the first element that is initialized.
    Compiler MSVC++ 2013 with Code::Blocks.

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
                number = number/2;
                total++; /* increasing by one each time will yield the
                            number of numbers in the array. */
    This section of code is repeated twice - once in each side of the "else".

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Ducky View Post
    Initialized to 0 or 3 doesnt make a difference. It was just an example.

    My point was that its the first element that is initialized.
    Considering that all variables being discussed are global, they should be all zero!

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #11
    Registered User
    Join Date
    Dec 2007
    Posts
    795
    Quote Originally Posted by matsp View Post
    Code:
                number = number/2;
                total++; /* increasing by one each time will yield the
                            number of numbers in the array. */
    This section of code is repeated twice - once in each side of the "else".

    --
    Mats
    Which is normal considering that after division with 2 you get 1 or 0.
    Compiler MSVC++ 2013 with Code::Blocks.

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Ducky View Post
    Which is normal considering that after division with 2 you get 1 or 0.
    Nah, you misunderstood the point of my post - you do the same thing on the if and else side of the if/else - that's called "code duplication", and should be avoided. You can just move those two lines of code to AFTER the if/else.

    Of course, you can do ALL of this without if/else - but that's probably pushing it a bit far. [But if you want to, consider what the possible values of x%2 are?]

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  13. #13
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Basically you just shouldn't use globals for something as simple as that (you don't even want the variables to keep their value between calls!) and the program is broken up into functions in a rather poor way: main does too little, while prog does too much - part of it should be done in main. A better lay-out would be something like that (using std::string as a convenient type for storing the binary representation):

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    //a function with a well-defined purpose
    string to_binary(int num)
    {
        //implementation of conversion
    }
    
    int main()
    {
        while (true) { //or rather: while (cin)
            int number;
            cout<<"Enter decimal to convert: ";
            cin>>number;
            cout << to_binary(number) << endl << endl;
        }
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  14. #14
    Registered User
    Join Date
    Dec 2007
    Posts
    795
    Thanks for the help Mats and Anon.

    I rewrote it, but i would still need to know how to put an int in a string.

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    string to_binary(int number)
    {
        string binary;
    
        while(number>=1)
        {
    	number = number%2;
    	binary = number;
        }
        return binary;
    }
    
    int main()
    {
        while (cin)
        {
            int number;
            cout << "Enter decimal to convert: ";
            cin >> number;
            cout << to_binary(number) << endl << endl;
    
        }
    }
    Last edited by Ducky; 04-22-2009 at 06:28 AM.
    Compiler MSVC++ 2013 with Code::Blocks.

  15. #15
    The larch
    Join Date
    May 2006
    Posts
    3,573
    You are probably going to need std::string a lot, so get familiar with it.

    The function might look like this:

    Code:
    string to_binary(int number)
    {
        string binary;
    
        while(number>=1)
        {
            //turn the numbers 0 or 1 into char's '0' or '1' and append to the string
            binary += (number % 2 + '0');
            number /= 2;
        }
        
        // the binary number is in reverse now
        //you could have added the characters to the beginning of the string earlier
        //but it's also simple just to reverse it:
        reverse(binary.begin(), binary.end()); //#include <algorithm>
        return binary;
    }
    For real programs you might also check out std::bitset.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need help with decimal to binary Algorithm
    By webznz in forum C Programming
    Replies: 4
    Last Post: 03-13-2008, 03:52 AM
  2. Confused by expression.
    By Hulag in forum C Programming
    Replies: 3
    Last Post: 04-07-2005, 07:52 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. binary to decimal
    By miryellis in forum C Programming
    Replies: 7
    Last Post: 03-14-2004, 07:35 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

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