Conversão Decimal em C++ para binário

eu escrevi um programa' simples ' (levou-me 30 minutos) que converte o número decimal em binário. Tenho a certeza que há uma maneira muito mais simples, por isso podes mostrar-me? Aqui está o código:

#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;
}
A propósito, é complicado, mas dei o meu melhor.

Edit - aqui está a solução que acabei por usar:

std::string toBinary(int n)
{
    std::string r;
    while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
    return r;
}
Author: Logman, 2014-03-30

21 answers

std::bitset tem um método .to_string() que devolve um std::string com uma representação de texto em binário, com enchimento zero à frente.

Escolha a largura do conjunto de bits conforme necessário para os seus dados, por exemplo std::bitset<32> para obter cadeias de 32 caracteres de inteiros de 32 bits.

#include <iostream>
#include <bitset>

int main()
{
    std::string binary = std::bitset<8>(128).to_string(); //to binary
    std::cout<<binary<<"\n";

    unsigned long decimal = std::bitset<8>(binary).to_ulong();
    std::cout<<decimal<<"\n";
    return 0;
}

Editar: Por favor não edite a minha resposta para Octal e Hexadecimal. O OP pediu especificamente para Decimal para binário.

 94
Author: Brandon, 2017-03-28 13:16:40

O seguinte é uma função recursiva que leva um inteiro positivo e imprime os seus dígitos binários para a consola.

Alex sugeriu, para eficiência, você pode querer remover printf() e armazenar o resultado na memória... dependendo do método de armazenamento o resultado pode ser revertido.

/**
 * Takes a positive integer, converts it into binary and prints it to the console.
 * @param n the number to convert and print
 */
void convertToBinary(unsigned int n)
{
    if (n / 2 != 0) {
        ConvertToBinary(n / 2);
    }
    printf("%d", n % 2);
}

Créditos à UoA ENGGEN 131

* Nota: o benefício de usar um int sem sinal é que ele não pode ser negativo.

 41
Author: Pathfinder, 2017-04-04 16:01:26

Uma solução bastante simples para imprimir o binário:

#include <iostream.h>

int main()
{
 int num,arr[64];
 cin>>num;
 int i=0,r;
 while(num!=0)
{
  r = num%2;
  arr[i++] = r;
  num /= 2;
}

for(int j=i-1;j>=0;j--)
 cout<<arr[j];
}
 7
Author: piyushtechsavy, 2015-01-02 09:50:28

Pode usar o 'std:: bitset' para converter um número para o seu formato binário.

Utilize o seguinte excerto de código:

std::string binary = std::bitset<8>(n).to_string();
Encontrei isto no stackoverflow. Estou anexando a ligação .
 7
Author: skpro19, 2017-05-23 11:47:17

Solução não recursiva:

#include <iostream>
#include<string>


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

Solução recursiva:

#include <iostream>
#include<string>

std::string r="";
std::string toBinary(int n)
{
    r=(n%2==0 ?"0":"1")+r;
    if (n / 2 != 0) {
        toBinary(n / 2);
    }
    return r;
}
int main()
{
    std::string i=toBinary(10);
    std::cout<<i;
}
 4
Author: abe312, 2015-12-10 20:24:11

Uma variável int não é decimal, é binária. O que você está procurando é uma representação em cadeia binária do número, que você pode obter aplicando uma máscara que filtra bits individuais, e então imprimindo-os:

for( int i = sizeof(value)*CHAR_BIT-1; i>=0; --i)
    cout << value & (1 << i) ? '1' : '0';
Essa é a solução se a tua pergunta for algorítmica. Caso contrário, deve utilizar a classe std:: bitset para tratar disto por si:
bitset< sizeof(value)*CHAR_BIT > bits( value );
cout << bits.to_string();
 4
Author: Alex, 2016-05-11 14:44:33
Aqui estão duas abordagens. Este é semelhante à sua abordagem
#include <iostream>
#include <string>
#include <limits>
#include <algorithm>

int main()
{
    while ( true )
    {
        std::cout << "Enter a non-negative number (0-exit): ";

        unsigned long long x = 0;
        std::cin >> x;

        if ( !x ) break;

        const unsigned long long base = 2;

        std::string s;
        s.reserve( std::numeric_limits<unsigned long long>::digits ); 

        do { s.push_back( x % base + '0' ); } while ( x /= base );

        std::cout << std::string( s.rbegin(), s.rend() )  << std::endl;
    }
}

And the other uses std:: bitset as others suggested.

#include <iostream>
#include <string>
#include <bitset>
#include <limits>

int main()
{
    while ( true )
    {
        std::cout << "Enter a non-negative number (0-exit): ";

        unsigned long long x = 0;
        std::cin >> x;

        if ( !x ) break;

        std::string s = 
            std::bitset<std::numeric_limits<unsigned long long>::digits>( x ).to_string();

        std::string::size_type n = s.find( '1' ); 
        std::cout << s.substr( n )  << std::endl;
    }
}
 3
Author: Vlad from Moscow, 2014-03-30 17:17:23

Queres fazer algo como:

cout << "Enter a decimal number: ";
cin >> a1;
cout << setbase(2);
cout << a1
 0
Author: JoeNahmias, 2014-03-30 16:25:34

DECIMAL com binário não são usadas matrizes * feitas por Oya:

Ainda sou um principiante, por isso este código só vai usar loops e variáveis xD...

Espero que gostes. Isto pode, provavelmente, tornar-se mais simples do que é...
    #include <iostream>
    #include <cmath>
    #include <cstdlib>

    using namespace std;

    int main()
    {
        int i;
        int expoentes; //the sequence > pow(2,i) or 2^i
        int decimal; 
        int extra; //this will be used to add some 0s between the 1s
        int x = 1;

        cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
        cout << "\n\nWARNING: Only works until ~1.073 millions\n";
        cout << "     To exit, enter a negative number\n\n";

        while(decimal >= 0){
            cout << "\n----- // -----\n\n";
            cin >> decimal;
            cout << "\n";

            if(decimal == 0){
                cout << "0";
            }
            while(decimal >= 1){
                i = 0;
                expoentes = 1;
                while(decimal >= expoentes){
                    i++;
                    expoentes = pow(2,i);
                }
                x = 1;
                cout << "1";
                decimal -= pow(2,i-x);
                extra = pow(2,i-1-x);
                while(decimal < extra){
                    cout << "0";
                    x++;
                    extra = pow(2,i-1-x);
                }
            }
        }
        return 0;
    }
 0
Author: João, 2015-09-12 14:23:46

Aqui um conversor simples usando std::string como recipiente. permite um valor negativo.

#include <iostream>
#include <string>
#include <limits>

int main()
{
    int x = -14;

    int n = std::numeric_limits<int>::digits - 1;

    std::string s;
    s.reserve(n + 1);

    do
        s.push_back(((x >> n) & 1) + '0');
    while(--n > -1);

    std::cout << s << '\n';
}
 0
Author: MORTAL, 2016-06-11 16:15:48

Este é um programa mais simples do que nunca

//Program to convert Decimal into Binary
#include<iostream>
using namespace std;
int main()
{
    long int dec;
    int rem,i,j,bin[100],count=-1;
    again:
    cout<<"ENTER THE DECIMAL NUMBER:- ";
    cin>>dec;//input of Decimal
    if(dec<0)
    {
        cout<<"PLEASE ENTER A POSITIVE DECIMAL";
        goto again;
    }
    else
        {
        cout<<"\nIT's BINARY FORM IS:- ";
        for(i=0;dec!=0;i++)//making array of binary, but reversed
        {
            rem=dec%2;
            bin[i]=rem;
            dec=dec/2;
            count++;
        }
        for(j=count;j>=0;j--)//reversed binary is printed in correct order
        {
            cout<<bin[j];
        }
    }
    return 0; 
}
 0
Author: Sonani Meet, 2017-09-02 04:49:36
Há, de facto, uma forma muito simples de o fazer. O que fazemos é usar uma função recursiva que é dado o número (int) no parâmetro. É muito fácil de entender. Você pode adicionar outras condições / variações também. Aqui está o código:
int binary(int num)
{
    int rem;
    if (num <= 1)
        {
            cout << num;
            return num;
        }
    rem = num % 2;
    binary(num / 2);
    cout << rem;
    return rem;
}
 0
Author: Sahil Shah, 2017-09-18 03:42:41
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main() {
    // Initialize Variables
    double x;
    int xOct;
    int xHex;

    //Initialize a variable that stores the order if the numbers in binary/sexagesimal base
    vector<int> rem;

    //Get Demical value
    cout << "Number (demical base): ";
    cin >> x;

    //Set the variables
    xOct = x;
    xHex = x;

    //Get the binary value
    for (int i = 0; x >= 1; i++) {
        rem.push_back(abs(remainder(x, 2)));
        x = floor(x / 2);
    }

    //Print binary value
    cout << "Binary: ";
    int n = rem.size();
    while (n > 0) {
        n--;
        cout << rem[n];
    } cout << endl;

    //Print octal base
    cout << oct << "Octal: " << xOct << endl;

    //Print hexademical base
    cout << hex << "Hexademical: " << xHex << endl;

    system("pause");
    return 0;
}
 0
Author: ניתאי דרעי, 2017-09-28 19:24:47
#include <iostream>
using namespace std;

int main()
{  
    int a,b;
    cin>>a;
    for(int i=31;i>=0;i--)
    {
        b=(a>>i)&1;
        cout<<b;
    }
}
 0
Author: Harutyun Khachatryan, 2017-10-29 18:30:48
HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY


  #include<iostream>
    using namespace std;
    int main()
    {
        int input,rem,res,count=0,i=0;
        cout<<"Input number: ";
        cin>>input;`enter code here`
        int num=input;
        while(input > 0)
        {
            input=input/2;  
            count++;
        }

        int arr[count];

        while(num > 0)
        {
            arr[i]=num%2;
            num=num/2;  
            i++;
        }
        for(int i=count-1 ; i>=0 ; i--)
        {
            cout<<" " << arr[i]<<" ";
        }



        return 0;
    }
 0
Author: A.siddiqui, 2017-11-09 13:28:35
std::string bin(uint_fast8_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}
 0
Author: q-l-p, 2017-11-20 17:01:22
// function to convert decimal to binary
void decToBinary(int n)
{
    // array to store binary number
    int binaryNum[1000];

    // counter for binary array
    int i = 0;
    while (n > 0) {

        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }

    // printing binary array in reverse order
    for (int j = i - 1; j >= 0; j--)
        cout << binaryNum[j];
}

:- https://www.geeksforgeeks.org/program-decimal-binary-conversion/

Ou usar a função: -

#include<bits/stdc++.h>
using namespace std;

int main()
{

    int n;cin>>n;
    cout<<bitset<8>(n).to_string()<<endl;


}

Ou usar o turno da esquerda

#include<bits/stdc++.h>
using namespace std;
int main()
{
    // here n is the number of bit representation we want 
    int n;cin>>n;

    // num is a number whose binary representation we want
    int num;
    cin>>num;

    for(int i=n-1;i>=0;i--)
    {
        if( num & ( 1 << i ) ) cout<<1;
        else cout<<0;
    }


}
 0
Author: mjp, 2018-04-24 11:38:09

Para isto, em C++ pode usar a função itoa ().Esta função converte qualquer número Decimal inteiro em Binário , decimal, hexadecimal e octal.

#include<bits/stdc++.h>
using namespace std;
int main(){
 int a;    
 char res[1000];
 cin>>a;
 itoa(a,res,10);
 cout<<"Decimal- "<<res<<endl;
 itoa(a,res,2);
 cout<<"Binary- "<<res<<endl;
 itoa(a,res,16);
 cout<<"Hexadecimal- "<<res<<endl;
 itoa(a,res,8);
 cout<<"Octal- "<<res<<endl;return 0;
}

No entanto, só é suportado por compiladores específicos.

Você também pode ver: Itoa - Referência em C++

 0
Author: Abhijoy Sarkar, 2018-07-09 12:35:35

Abaixo está um código C simples que converte binário em decimal e volta. Eu escrevi isso há muito tempo para um projeto no qual o alvo era um processador embutido e as ferramentas de desenvolvimento tinham um stdlib que era maneira Muito Grande para a ROM firmware.

Este é um código C genérico que não usa nenhuma biblioteca, nem usa a divisão ou o operador restante ( % ) (que é lento em alguns processadores embutidos), nem usa qualquer ponto flutuante, nem usa qualquer pesquisa de tabela nem emular qualquer aritmética BCD. O que ele faz uso é do tipo long long, mais especificamente unsigned long long (ou uint64), Então se o seu processador embutido (e o compilador C que vai com ele) não pode fazer aritmética de 64-bits inteiros, este código não é para a sua aplicação. Caso contrário, penso que se trata de um código de qualidade da produção C (Talvez depois de ter mudado long para int32 e unsigned long long para uint64). Executei isto de um dia para o testar para cada valor inteiro de 2^32 assinado e não há nenhum erro na conversão em qualquer Direccao.

Tínhamos um compilador C / linker que podia gerar executáveis e precisávamos de fazer o que podíamos sem qualquer stdlib (que era um porco). Então não printf() nem scanf(). Nem sequer um sprintf() nem sscanf(). Mas nós ainda tinha uma interface de usuário e tinha que converter números base-10 em binário e de volta. (Nós também fizemos a nossa própria utilidade malloc()-como a utilidade também e nossas próprias funções matemáticas transcendentais também.)

Então foi assim que o fiz (o programa e chamadas) para stdlib estavam lá para testar esta coisa no meu mac, Não para o código incorporado). Além disso, como alguns sistemas dev mais antigos não reconhecem "int64" e "uint64" e tipos semelhantes, os tipos long long e unsigned long long são usados e presumidos como sendo os mesmos. E long supõe-se que sejam 32 bits. Acho que podia tê-lo feito.
// returns an error code, 0 if no error,
// -1 if too big, -2 for other formatting errors
int decimal_to_binary(char *dec, long *bin)
    {
    int i = 0;

    int past_leading_space = 0;
    while (i <= 64 && !past_leading_space)        // first get past leading spaces
        {
        if (dec[i] == ' ')
            {
            i++;
            }
         else
            {
            past_leading_space = 1;
            }
        }
    if (!past_leading_space)
        {
        return -2;                                // 64 leading spaces does not a number make
        }
    // at this point the only legitimate remaining
    // chars are decimal digits or a leading plus or minus sign

    int negative = 0;
    if (dec[i] == '-')
        {
        negative = 1;
        i++;
        }
     else if (dec[i] == '+')
        {
        i++;                                    // do nothing but go on to next char
        }
    // now the only legitimate chars are decimal digits
    if (dec[i] == '\0')
        {
        return -2;                              // there needs to be at least one good 
        }                                       // digit before terminating string

    unsigned long abs_bin = 0;
    while (i <= 64 && dec[i] != '\0')
        {
        if ( dec[i] >= '0' && dec[i] <= '9' )
            {
            if (abs_bin > 214748364)
                {
                return -1;                                // this is going to be too big
                }
            abs_bin *= 10;                                // previous value gets bumped to the left one digit...                
            abs_bin += (unsigned long)(dec[i] - '0');     // ... and a new digit appended to the right
            i++;
            }
         else
            {
            return -2;                                    // not a legit digit in text string
            }
        }

    if (dec[i] != '\0')
        {
        return -2;                                // not terminated string in 64 chars
        }

    if (negative)
        {
        if (abs_bin > 2147483648)
            {
            return -1;                            // too big
            }
        *bin = -(long)abs_bin;
        }
     else
        {
        if (abs_bin > 2147483647)
            {
            return -1;                            // too big
            }
        *bin = (long)abs_bin;
        }

    return 0;
    }


void binary_to_decimal(char *dec, long bin)
    {
    unsigned long long acc;                // 64-bit unsigned integer

    if (bin < 0)
        {
        *(dec++) = '-';                    // leading minus sign
        bin = -bin;                        // make bin value positive
        }

    acc = 989312855LL*(unsigned long)bin;        // very nearly 0.2303423488 * 2^32
    acc += 0x00000000FFFFFFFFLL;                 // we need to round up
    acc >>= 32;
    acc += 57646075LL*(unsigned long)bin;
    // (2^59)/(10^10)  =  57646075.2303423488  =  57646075 + (989312854.979825)/(2^32)  

    int past_leading_zeros = 0;
    for (int i=9; i>=0; i--)            // maximum number of digits is 10
        {
        acc <<= 1;
        acc += (acc<<2);                // an efficient way to multiply a long long by 10
//      acc *= 10;

        unsigned int digit = (unsigned int)(acc >> 59);        // the digit we want is in bits 59 - 62

        if (digit > 0)
            {
            past_leading_zeros = 1;
            }

        if (past_leading_zeros)
            {
            *(dec++) = '0' + digit;
            }

        acc &= 0x07FFFFFFFFFFFFFFLL;    // mask off this digit and go on to the next digit
        }

    if (!past_leading_zeros)            // if all digits are zero ...
        {
        *(dec++) = '0';                 // ... put in at least one zero digit
        }

    *dec = '\0';                        // terminate string
    }


#if 1

#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
    {
    char dec[64];
    long bin, result1, result2;
    unsigned long num_errors;
    long long long_long_bin;

    num_errors = 0;
    for (long_long_bin=-2147483648LL; long_long_bin<=2147483647LL; long_long_bin++)
        {
        bin = (long)long_long_bin;
        if ((bin&0x00FFFFFFL) == 0)
            {
            printf("bin = %ld \n", bin);        // this is to tell us that things are moving along
            }
        binary_to_decimal(dec, bin);
        decimal_to_binary(dec, &result1);
        sscanf(dec, "%ld", &result2);            // decimal_to_binary() should do the same as this sscanf()

        if (bin != result1 || bin != result2)
            {
            num_errors++;
            printf("bin = %ld, result1 = %ld, result2 = %ld, num_errors = %ld, dec = %s \n",
                bin, result1, result2, num_errors, dec);
            }
        }

    printf("num_errors = %ld \n", num_errors);

    return 0;
    }

#else

#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
    {
    char dec[64];
    long bin;

    printf("bin = ");
    scanf("%ld", &bin);
    while (bin != 0)
        {
        binary_to_decimal(dec, bin);
        printf("dec = %s \n", dec);
        printf("bin = ");
        scanf("%ld", &bin);
        }

    return 0;
    }

#endif
 0
Author: robert bristow-johnson, 2018-07-19 03:55:34
#include <iostream>
#include <bitset>

#define bits(x)  (std::string( \
            std::bitset<8>(x).to_string<char,std::string::traits_type, std::string::allocator_type>() ).c_str() )


int main() {

   std::cout << bits( -86 >> 1 ) << ": " << (-86 >> 1) << std::endl;

   return 0;
}
 0
Author: Yuriy Gyerts, 2018-09-24 11:20:36
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

void Decimal2Binary(long value,char *b,int len)
{
    if(value>0)
    {
        do
        {
            if(value==1)
            {
                *(b+len-1)='1';
                break;
            }
            else
            {
                *(b+len-1)=(value%2)+48;
                value=value/2;
                len--;
            }
        }while(1);
    }
}
long Binary2Decimal(char *b,int len)
{
    int i=0;
    int j=0;
    long value=0;
    for(i=(len-1);i>=0;i--)
    {
        if(*(b+i)==49)
        {
            value+=pow(2,j);
        }
        j++;
    }
    return value;
}
int main()
{
    char data[11];//最後一個BIT要拿來當字串結尾
    long value=1023;
    memset(data,'0',sizeof(data));
    data[10]='\0';//字串結尾
    Decimal2Binary(value,data,10);
    printf("%d->%s\n",value,data);
    value=Binary2Decimal(data,10);
    printf("%s->%d",data,value);
    return 0;
}
 -2
Author: jash.liao, 2016-04-28 08:41:29