C++ - Konvertierung von Dezimal nach Binär

Ich habe ein 'einfaches' (es hat mich 30 Minuten gekostet) Programm geschrieben, das Dezimalzahlen in Binärzahlen umwandelt. Ich bin SICHER, dass es einen viel einfacheren Weg gibt, können Sie ihn mir zeigen? Hier's der Code:

#include <iostream>
#include <stdlib.h>

using namespace std;
int a1, a2, remainder;
int tab = 0;
int maxtab = 0;
int table[0];
int main()
{
    system("clear");
    cout << "Enter a decimal number: ";
    cin >> a1;
    a2 = a1; //we need our number for later on so we save it in another variable

    while (a1!=0) //dividing by two until we hit 0
    {
        remainder = a1%2; //getting a remainder - decimal number(1 or 0)
        a1 = a1/2; //dividing our number by two
        maxtab++; //+1 to max elements of the table
    }

    maxtab--; //-1 to max elements of the table (when dividing finishes it adds 1 additional elemnt that we don't want and it's equal to 0)
    a1 = a2; //we must do calculations one more time so we're gatting back our original number
    table[0] = table[maxtab]; //we set the number of elements in our table to maxtab (we don't get 10's of 0's)

    while (a1!=0) //same calculations 2nd time but adding every 1 or 0 (remainder) to separate element in table
    {
        remainder = a1%2; //getting a remainder
        a1 = a1/2; //dividing by 2
        table[tab] = remainder; //adding 0 or 1 to an element
        tab++; //tab (element count) increases by 1 so next remainder is saved in another element
    }

    tab--; //same as with maxtab--
    cout << "Your binary number: ";

    while (tab>=0) //until we get to the 0 (1st) element of the table
    {
        cout << table[tab] << " "; //write the value of an element (0 or 1)
        tab--; //decreasing by 1 so we show 0's and 1's FROM THE BACK (correct way)
    }

    cout << endl;
    return 0;
}

Übrigens, es ist kompliziert, aber ich habe mein Bestes gegeben.

edit - Hier ist die Lösung, die ich am Ende verwendet habe:

std::string toBinary(int n)
{
    std::string r;
    while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
    return r;
}

[std::bitset][1] hat eine .to_string() Methode, die einen std::string zurückgibt, der eine Textrepräsentation in Binärform enthält, mit führenden Nullen zum Auffüllen.

Wählen Sie die Breite des Bitsets so, wie Sie es für Ihre Daten benötigen, z.B. std::bitset, um 32-Zeichen-Strings aus 32-Bit-Integern zu erhalten.


#include 
#include 

int main()
{
    std::string binary = std::bitset(128).to_string(); //to binary
    std::cout
Kommentare (3)

Eine int-Variable ist nicht dezimal, sondern binär. Was Sie suchen, ist eine binäre Zeichenkettendarstellung der Zahl, die Sie erhalten können, indem Sie eine Maske anwenden, die einzelne Bits filtert, und sie dann ausdrucken:


for( int i = sizeof(value)*CHAR_BIT-1; i>=0; --i)
    cout 
Kommentare (0)

Sie wollen etwas tun wie:


cout > a1;
cout 
Kommentare (1)