C++ - Decimal to binary converting

424,886

Solution 1

std::bitset has a .to_string() method that returns a std::string holding a text representation in binary, with leading-zero padding.

Choose the width of the bitset as needed for your data, e.g. std::bitset<32> to get 32-character strings from 32-bit integers.

#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: Please do not edit my answer for Octal and Hexadecimal. The OP specifically asked for Decimal To Binary.

Solution 2

The following is a recursive function which takes a positive integer and prints its binary digits to the console.

Alex suggested, for efficiency, you may want to remove printf() and store the result in memory... depending on storage method result may be reversed.

/**
 * Takes a unsigned 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);
}

Credits to UoA ENGGEN 131

*Note: The benefit of using an unsigned int is that it can't be negative.

Solution 3

You can use std::bitset to convert a number to its binary format.

Use the following code snippet:

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

I found this on stackoverflow itself. I am attaching the link.

Solution 4

A pretty straight forward solution to print binary:

#include <iostream>
using namespace std;
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];
  }
}

Solution 5

Non recursive solution:

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

Recursive solution:

#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;
}
Share:
424,886
user3478487
Author by

user3478487

Updated on January 02, 2022

Comments

  • user3478487
    user3478487 over 2 years

    I wrote a 'simple' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there's a lot simpler way so can you show me? Here's the 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;
    }
    

    By the way it's complicated but I tried my best.

    edit - Here is the solution I ended up using:

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