C++ - conversion décimale en binaire

j'ai écrit un programme 'simple' (il m'a fallu 30 minutes) qui convertit le nombre décimal en binaire. Je suis sûr qu'il y a un moyen plus simple de le faire, alors pouvez-vous me le montrer? Voici le 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;
}

au fait, c'est compliqué, mais j'ai fait de mon mieux.

edit-Voici la solution que j'ai fini par utiliser:

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

21 réponses

std::bitset a une méthode .to_string() qui renvoie une std::string contenant une représentation de texte en binaire, avec un rembourrage menant-zéro.

choisissez la largeur du bitset nécessaire à vos données, par exemple std::bitset<32> pour obtenir des chaînes de 32 caractères à partir d'entiers 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;
}

EDIT: Merci de ne pas éditer ma réponse pour l'Octal et Hexadécimal. Le PO demandait expressément Décimal En Binaire.

94
répondu Brandon 2017-03-28 13:16:40

ce qui suit est une fonction récursive qui prend un entier positif et imprime ses chiffres binaires sur la console.

Alex suggéré, pour l'efficacité, vous pourriez vouloir supprimer printf() et stocker le résultat en mémoire... selon méthode de stockage de résultat peut être inversé.

/**
 * 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édits à UoA ENGGEN 131

* Note: l'avantage d'utiliser un int non signé est qu'il ne peut pas être négatif.

41
répondu Pathfinder 2017-04-04 16:01:26

Une simple solution pour imprimer binaire:

#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
répondu piyushtechsavy 2015-01-02 09:50:28

Vous pouvez utiliser std::bitset pour convertir un nombre binaire en format.

utiliser l'extrait de code suivant:

std::string binary = std::bitset<8>(n).to_string();

j'ai trouvé ça sur stackoverflow lui-même. Je joins le lien .

7
répondu skpro19 2017-05-23 11:47:17

Non solution récursive:

#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;
}

solution Récursive:

#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
répondu abe312 2015-12-10 20:24:11

an int la variable n'est pas en décimal, elle est en binaire. Ce que vous recherchez est une représentation en chaîne binaire du nombre, que vous pouvez obtenir en appliquant un masque qui filtre les bits individuels, puis en les imprimant:

for( int i = sizeof(value)*CHAR_BIT-1; i>=0; --i)
    cout << value & (1 << i) ? '1' : '0';

c'est la solution si votre question Est algorithmique. Si non, vous devez utiliser la classe std::bitset pour gérer ceci pour vous:

bitset< sizeof(value)*CHAR_BIT > bits( value );
cout << bits.to_string();
4
répondu Alex 2016-05-11 14:44:33

Voici deux approches. Celle-ci est similaire à votre approche

#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;
    }
}

et les autres utilisations std::bitset comme d'autres l'ont suggéré.

#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
répondu Vlad from Moscow 2014-03-30 17:17:23

Vous voulez faire quelque chose comme:

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

tableaux décimaux à binaires de NO utilisés *fabriqués par Oya:

je suis encore débutant, donc ce code n'utilisera que des boucles et des variables xD...

J'espère que ça vous plaira. Cela peut probablement être plus simple qu'elle ne l'est...

    #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
répondu João 2015-09-12 14:23:46

ici un convertisseur simple en utilisant std::string comme conteneur. il permet une valeur négative.

#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
répondu MORTAL 2016-06-11 16:15:48

C'est un plus simple programme que jamais

//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
répondu Sonani Meet 2017-09-02 04:49:36

il y a en fait une façon très simple de le faire. Ce que nous faisons est d'utiliser une fonction récursive qui est donnée le nombre (int) dans le paramètre. Il est assez facile à comprendre. Vous pouvez également ajouter d'autres conditions / variations. Voici le code:

int binary(int num)
{
    int rem;
    if (num <= 1)
        {
            cout << num;
            return num;
        }
    rem = num % 2;
    binary(num / 2);
    cout << rem;
    return rem;
}
0
répondu 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
répondu ניתאי דרעי 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
répondu 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
répondu 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
répondu 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];
}

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

ou utilisation de la fonction: -

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

int main()
{

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


}

ou utilisation du décalage de gauche

#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
répondu mjp 2018-04-24 11:38:09

pour cela , en C++ vous pouvez utiliser la fonction itoa ().Cette fonction convertit n'importe quel nombre entier décimal en nombre binaire, décimal , hexadécimal et 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;
}

cependant, il n'est supporté que par des compilateurs spécifiques.

vous pouvez voir aussi: itoa - C++ Référence

0
répondu Abhijoy Sarkar 2018-07-09 12:35:35

ci-dessous est le code C simple qui convertit binaire en décimal et de nouveau. Je l'ai écrit il y a longtemps pour un projet dans lequel la cible était un processeur intégré et les outils de développement avaient un stdlib qui était way trop grand pour le firmware ROM.

il s'agit d'un code C générique qui n'utilise aucune Bibliothèque, pas plus qu'il n'utilise l'opérateur division ou le reste ( % ) (qui est lent sur certains processeurs intégrés), ni n'utilise de point flottant, il n'utilise pas non plus de recherche de table et n'émule pas D'arithmétique BCD. Ce qu'il fait usage de est le type long long , plus spécifiquement unsigned long long (ou uint64 ), donc si votre processeur intégré (et le compilateur C qui va avec) ne peut pas faire l'arithmétique entière 64 bits, ce code n'est pas pour votre application. Sinon, je pense que c'est le code de qualité de production C (peut-être après avoir changé long en int32 et unsigned long long en uint64 ). J'ai exécuté cette nuit pour le tester pour chaque 2^32 valeurs entières signées et il n'y a pas d'erreur dans la conversion dans les deux sens.

nous avions un compilateur/linker C qui pouvait générer des exécutables et nous avions besoin de faire ce que nous pouvions faire sans aucun stdlib (qui était un cochon). Donc pas de printf() ni scanf() . Pas même un sprintf() ou sscanf() . Mais nous encore avait une interface utilisateur et a dû convertir la base-10 numéros en binaire et retour. (Nous nous avons également créé notre propre utilité malloc() - comme et nos propres fonctions mathématiques transcendantales aussi.)

donc c'est comme ça que je l'ai fait (le programme main et les appels à stdlib étaient là pour tester cette chose sur mon mac, pas pour le code embarqué). En outre, parce que certains systèmes dev plus anciens ne reconnaissent pas " int64 " et " uint64 " et des types similaires, les types long long et unsigned long long sont utilisés et supposés être les mêmes. Et long est supposé être 32 bits. Je suppose que j'aurais pu typedef l'éditer.

// 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] == '"151900920"')
        {
        return -2;                              // there needs to be at least one good 
        }                                       // digit before terminating string

    unsigned long abs_bin = 0;
    while (i <= 64 && dec[i] != '"151900920"')
        {
        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] != '"151900920"')
        {
        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 = '"151900920"';                        // 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
répondu 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
répondu 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]='"151900920"';//字串結尾
    Decimal2Binary(value,data,10);
    printf("%d->%s\n",value,data);
    value=Binary2Decimal(data,10);
    printf("%s->%d",data,value);
    return 0;
}
-2
répondu jash.liao 2016-04-28 08:41:29