Thread: Easy way for decimal-binary conversion?

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    22

    Easy way for decimal-binary conversion?

    For a little challenge exercise i was doing i had to come up with a program that would take a decimal number as input and output it in binary form (ie 36 = 100100). I was successful in doing this, but only with a long, complicated program that mathematically converted them. I figure since everything in a computer's memory is in binary anyway, there should be a much easier way to just tell it to print the raw binary value of the integer variable. Is there such a way?

    BTW, here is the long, complicated (but working none-the-less) method that i came up with:

    Code:
    #include <iostream>
    #include <cstring>
    using namespace std;
    
    float pwr(int b, int e);
    
    int main()
    {
     float value, remainder;
     int largest_digit, power;
     bool done = 0;
     char in_binary[255];
     cout << "Enter the number: \n";
     cin >> value;
     cin.ignore();
     for (int x = 0; done == 0; x++)
     {
         if ((value / pwr(2, x)) < 2)
         {
             largest_digit = x;
             done = 1;
         }
     }
     done = 0;
     remainder = value;
     power = largest_digit;
     for (int x = 0; power >= 0; x++)
     {
         if ((remainder / pwr(2, power)) >= 1)
         {
             in_binary[x] = '1';
             remainder = (remainder - pwr(2, power));
         }
         else
         {
             in_binary[x] = '0';
         }
         power = (power - 1);
     }
     in_binary[(largest_digit + 1)] = '\0';
     cout << "\n" << in_binary << "\n";
     system("pause");
     
    
                      
    }
    
    float pwr(int b, int e)
    {
        if (e != 0)
        {
            int n;
            n = b;
            for (int x = 0; x < (e - 1); x++)
            {
                n = (n * b);
            }
            return float(n);
        }
        else
        {
            return 1;
        }
    }
    OK so I just put that in cuz its the first program i've ever written longer than 10 or so lines and i was pretty proud of myself

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    The STL <bitset> will do what you want for positive integers:
    Code:
    #include <iostream>
    #include <bitset>
    
    using namespace std;
    
    int main()
    {
    	unsigned long decNumber = 10;
    	bitset<16> biNumber(decNumber);
    	
    	int len = static_cast<int>(biNumber.size());  
    	
    	for(int i = len - 1; i >= 0; i--)
    	{
    		cout<<biNumber[i];
    		if(i % 4 == 0) cout<<" ";
    	}
    	cout<<endl;
    	
    	return 0;	
    }
    Note a bitset is ordered from right to left:

    index 15--->0000 0000 0000 1010<----index 0

    As for the static_cast, the size() function returns a size_t type, which is an unsigned short(positive integers below a certain size). Since you have to count down the loop to 0, using a size_t type for the loop control 'i' won't work, e.g.:
    Code:
    size_t len = biNumber.size();
    for(size_t i = len; i >= 0; i--)
    The last time through the loop i gets decremented to -1 which causes the loop to end, but before the loop can end the program will crash. 'i' is a size_t type(=unsigned short), so it has to be a positive integer. Therefore, decrementing i to -1 is not allowed and it will cause the program to crash. That's why i has to be an int, so it can be negative, and casting the return value from size() was necessary.
    Last edited by 7stud; 11-02-2005 at 01:07 AM.

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    When bored:
    Code:
    #include <iostream>
    #include <string>
    #include <cmath>
    #include <limits>
    
    int main()
    {
            using namespace std;
            const unsigned numbits = static_cast<int>(
                                    ceil(
                                            log(double(numeric_limits<unsigned>::max()))
                                            /
                                            log(double(2))
                                    )
                            );
    
            unsigned div = static_cast<unsigned>(pow(double(2), double(numbits-1)));
    
            string bin;
    
            unsigned num = 45329;
            // 1011000100010001
    
            while ( div != 0 )
            {
                    if ( div <= num )
                    {
                            bin.push_back('1');
                            num -= div;
                    }
                    else
                    {
                            if ( bin.size() != 0 )
                                    bin.push_back('0');
                    }
                    div /= 2;
            }
            cout<<"Predefined value: 1011000100010001"<<endl;
            cout<<"Experiment value: "<<bin<<endl;
    }

  4. #4
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    Not bad, though I don't know why you're using floats sometimes.

    Your intuition is correct. Two operators in C are known as the bit shifting operators. They are '<<' and '>>'. (They are used in a different way when dealing with input and output streams.) Essentially, they multiply integers by powers of two. (x << y) multiplies x by two to the y'th power. (x >> y) divides x by two to the y'th power (rounding down).

    For example, 32 >> 3 == 4. Also, 4 << 3 == 32. You can compute 2 to the nth power with the expression (1 << n). These operations are very efficient.

    You can get the least-significant bit of a number by calculating the remainder when dividing by 2. For example, the least significant bit of 7 is 1, because 7 is odd. (Its binary representation is 111.) Whereas 6 is 110, so its least significant bit is zero.

    So x % 2 returns the least-significant bit of x. And x >> 1 divides x by two (moving all the bits of the binary representation over by one position). Here's a program:

    Code:
    #include <iostream>
    using std::cout; using std::endl; using std::cin;
    
    int main() {
      unsigned int inp;
      char binary_str[33];
      // A length of 33 is chosen with the (unfounded) assumption that unsigned
      // integers are only 32 bits long, maximum.  This is usually the case, but
      // instead, I would use #include <string> and use the std::string datatype, to
      // avoid overflowing the array bounds.  (If I were to compile this code for a
      // machine that uses sixty-four bit integers, the array could overflow.)
    
      cout << "Enter your number: ";
      cin >> inp;
    
      int w = 0;
      while (inp != 0) {
    
        if (inp % 2 == 0) {
          binary_str[w] = '0';
        } else {
          binary_str[w] = '1';
        }
    
        // The above if-then-else statement could be simplified by writing:
        //     binary_str[w] = '0' + inp % 2;
        // but let's not get ahead of ourselves.
    
        w = w + 1;
    
        inp = inp >> 1; // Shift the bits over by a position.
      }
    
      binary_str[w] = '\0';
    
      cout << "\n" << binary_str << endl;
    
      return 0;
    }
    Unfortunately, this string is written out backwards! (You can fix this, right?)

  5. #5
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    My 2 cents :-)

    I originally didn't use stringstream and just outputted the answer directly, however this way, you will be able to use the answer elsewhere.

    Code:
    #include <iostream>
    #include <sstream>
    using namespace std;
    
    
    int main()
    {
    
    	stringstream ss;
    	unsigned value, bit = 2147483648, index = 32;
    
    	cout << "Enter the number: \n";
    	cin >> value;
    
    	while (index--)
    		ss << ((value & bit)&&true),bit >>= 1;
    
    	cout << "\n" << ss.str() << "\n";
    	system("pause");
    }
    Functionized
    Code:
    #include <sstream>
    using namespace std;
    std::string dec2bin(unsigned value)
    {
    	stringstream ss;
    	unsigned bit = 2147483648, index =32;
    	while (index--)	ss << ((value & bit) && true), bit >>= 1;
    	return ss.str();
    }
    Last edited by Darryl; 11-02-2005 at 09:56 AM. Reason: further optimaizations

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary conversion..
    By shwetha_siddu in forum C Programming
    Replies: 3
    Last Post: 07-31-2008, 03:24 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Binary comparison
    By tao in forum Windows Programming
    Replies: 0
    Last Post: 06-28-2006, 12:10 PM
  4. Decimal to binary conversion
    By blckspder in forum C Programming
    Replies: 5
    Last Post: 04-07-2005, 12:38 PM
  5. Creation of Menu problem
    By AQWst in forum C Programming
    Replies: 8
    Last Post: 11-24-2004, 09:44 PM