简体   繁体   中英

convert decimal to 32 bit binary?

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?

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.

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

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.

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 .

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.

Recursion. In pseudocode:

function toBinary(integer num)
  if (num < 2) 
  then
    print(num)
  else
    toBinary(num DIV 2)
    print(num MOD 2)
  endif
endfunction

This does not handle leading zeros or negative numbers. The recursion stack is used to reverse the binary bits into the standard order.

Just write:

long int dec,rem,i=1,sum=0  

Instead of:

int dec,rem,i=1,sum=0;

That should solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM