convert decimal to 32 bit binary?

19,250

Solution 1

Using a for-loop, and a predefined array of zero-chars:

#include <iostream>
using namespace std;
int main()
{
    int dec;
    cout << "Enter the decimal to be converted: ";
    cin >> dec;

    char bin32[]  = "00000000000000000000000000000000";
    for (int pos = 31; pos >= 0; --pos)
    {
        if (dec % 2) 
            bin32[pos] = '1';
        dec /= 2;
    }

    cout << "The binary of the given number is: " << bin32 << endl;
}

For performance reasons, you may prematurely suspend the for loop:

    for (int pos = 31; pos >= 0 && dec; --pos)

Note, that in C++, you can treat an integer as a boolean - everything != 0 is considered true.

Solution 2

What you get in sum as a result is hardly usable for anything but printing. It's a decimal number which just looks like a binary.

If the decimal-binary conversion is not an end in itself, note that numbers in computer memory are already represented in binary (and it's not the property of C++), and the only thing you need is a way to print it. One of the possible ways is as follows:

int size = 0;
for (int tmp = dec; tmp; tmp >>= 1)
    size++;
for (int i = size - 1; i >= 0; --i)
    cout << ((dec >> i) & 1);

Another variant using a character array:

char repr[33] = { 0 };
int size = 0;
for (int tmp = dec; tmp; tmp >>= 1)
    size++;
for (int i = 0; i < size; ++i)
    repr[i] = ((dec >> (size - i - 1)) & 1) ? '1' : '0';
cout << repr << endl;

Note that both variants don't work if dec is negative.

Solution 3

You have a number and want its binary representation, i.e, a string. So, use a string, not an numeric type, to store your result.

Solution 4

You could use an unsigned integer type. However, even with a larger type you will eventually run out of space to store binary representations. You'd probably be better off storing them in a string.

Solution 5

As others have pointed out, you need to generate the results in a string. The classic way to do this (which works for any base between 2 and 36) is:

std::string
toString( unsigned n, int precision, unsigned base )
{
    assert( base >= 2 && base <= 36 );
    static char const digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string retval;
    while ( n != 0 ) {
        retval += digits[ n % base ];
        n /= base;
    }
    while ( retval.size() < precision ) {
        retval += ' ';
    }
    std::reverse( retval.begin(), retval.end() );
    return retval;
}

You can then display it.

Share:
19,250
Ronaldinho Learn Coding
Author by

Ronaldinho Learn Coding

Updated on June 06, 2022

Comments

  • Ronaldinho Learn Coding
    Ronaldinho Learn Coding almost 2 years

    convert a positive integer number in C++ (0 to 2,147,483,647) to a 32 bit binary and display.

    I want do it in traditional "mathematical" way (rather than use bitset or use vector *.pushback* or recursive function or some thing special in C++...), (one reason is so that you can implement it in different languages, well maybe)

    So I go ahead and implement a simple program like this:

    #include <iostream>
    using namespace std;
    int main()
    {
        int dec,rem,i=1,sum=0;
        cout << "Enter the decimal to be converted: ";
        cin>>dec;
        do
        {
            rem=dec%2;
            sum=sum + (i*rem);
            dec=dec/2;
            i=i*10;
        } while(dec>0);
    
        cout <<"The binary of the given number is: " << sum << endl;
    
        system("pause");
        return 0;
    }
    

    Problem is when you input a large number such as 9999, result will be a negative or some weird number because sum is integer and it can't handle more than its max range, so you know that a 32 bit binary will have 32 digits so is it too big for any number type in C++?. Any suggestions here and about display 32 bit number as question required?

  • Ronaldinho Learn Coding
    Ronaldinho Learn Coding about 12 years
    ok any suggestion if use string to represent 32 bit binary number? if you enter 5, binary is 101 but it have to be 29 '0' digits before 101?
  • Ronaldinho Learn Coding
    Ronaldinho Learn Coding about 12 years
    question required to display 32 bit binary number, that's why?
  • dirkgently
    dirkgently about 12 years
    @LongBodie: Then yes, you will need to zero-pad your string.
  • bames53
    bames53 about 12 years
    The fact that the value is physically represented as binary in memory isn't particularly relevant to printing the binary representation this way, just as printing it in decimal doesn't require the value to be physically represented in decimal. For example, the >> operator in C++ is defined in powers of two, so even on a ternary system it would produce the same values (though it would be more expensive).
  • Alex Bakulin
    Alex Bakulin about 12 years
    @bames53 If the number is represented, say, in ternary, then in order to print it in ternary we don't need to convert it like operator >> does. It'd be enough to just read and print the stored digits.
  • bames53
    bames53 about 12 years
    "It'd be enough to just read and print the stored digits." My point can be restated in the following way; that accessing ternary digits on a ternary machine looks just like the arithmetic you'd do on any other machine to produce the ternary representation. I.e. a bunch of divides and mods by 3. In that sense the physical representation is irrelevant. Similarly, producing a binary representation looks the same whether you're on a decimal, ternary or binary machine.
  • Alex Bakulin
    Alex Bakulin about 12 years
    @bames53 Now I see your point. You're right. My mistake was in thinking that on ternary machine operator >> would have "shift one ternary digit right" semantics.
  • kleopatra
    kleopatra almost 11 years
    hmm ... long int - are you sure? Anyway, please edit your answer and format the code (4 spaces at line start, ctrl-k is your friend :)