Results 1 to 3 of 3

Thread: How to convert a decimal number to a binary one in C++

  1. #1
    Member
    Join Date
    May 2012
    Posts
    33

    Post How to convert a decimal number to a binary one in C++

    Hi all,

    I need to write a program that converts a decimal number to a binary one.
    I have implemented almost all the code. I got the bit problem
    EX:
    Code:
    22->00011010
    but I am getting 0001101
    the last bit is missing.

    Here is my code,

    #include <iostream>
    using namespace std;
    This is my conversion function
    Code:
    void D2B(int Val1) 
    {
        int Rem = 0;
     
        Val1 = Val1 / 2;
        Rem = Val1 % 2;
            
            if (Val1 > 0)
            {
                    D2B(Val1);
                    
            }
            else if (Val1 = 0)
            {
                    cout << "0";
                    return;
            }
     
            cout << Rem;  
    }
    My main function
    Code:
    int main() 
    {
        int Val1 = 0;
     
        cout << "Enter the positive value ";
        cin >> Val1;
       
            if (Val1 < 0)
            {
            cout << endl << "Enter valid val" << endl << endl;
            }
            else 
            {
            cout << endl << "After Conversion " << Val1 << " = ";
            D2B(Val1);
            cout << endl << endl;
            }
    
            return 0;
    }
    can anyone please help me what is the wrong in my code..

  2. #2
    Senior Member sarvani's Avatar
    Join Date
    May 2012
    Posts
    173
    Just calculate the remainder before dividing.

    Code:
     Val1 = Val1 / 2;
        Rem = Val1 % 2;

  3. #3
    Senior Member suve's Avatar
    Join Date
    Jun 2012
    Posts
    441
    Code:
    void D2B ( const int Val1)
    {
       if( Val1== 0 )
       {
          return;
       }
    
       D2B ( Val1/2 );
       cout << Val1% 2;
    }

Similar Threads

  1. Replies: 0
    Last Post: 02-18-2013, 09:29 AM
  2. Replies: 0
    Last Post: 12-29-2012, 05:33 AM
  3. Replies: 0
    Last Post: 10-31-2012, 10:59 AM
  4. Replies: 0
    Last Post: 10-19-2012, 11:53 AM
  5. Convert the Decimal value to Hex valu in C++
    By Bandhavi in forum Programming languages
    Replies: 1
    Last Post: 07-10-2012, 09:44 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •