oni-kun
oni-kun

Reputation: 1825

How would I convert decimal into binary?

All I really know is PHP and I used the decbin function etc, It was fairly easy to do. In this C++ program I want to do the same thing, just a simple number or string how would I do this?

Upvotes: 0

Views: 10535

Answers (7)

Kulamani
Kulamani

Reputation: 517

Do with simple way in c++

#include <iostream>
using namespace std;
int main()
{
long n, rem, binary=0, i=1;
cout<<"Enter a int: ";
cin>>n;

 while(n != 0) 
   {
        rem = n%2;      
        n = n/2;        
        binary= binary + (rem*i); 
        i = i*10;
    }
cout<< "\nAns:   "<<binary <<endl;

return 0;
}

Upvotes: 0

Caesar De la Paz III
Caesar De la Paz III

Reputation: 387

Similar to @Necrolis answer without the need for an if, and the reversal of the string.

string decimalToBinary(int decimal) {
  string binary;
  while(decimal)  {
      binary.insert(0, 1, (decimal & 1) + '0');
      decimal >>= 1;
  }
  return binary;
}

Upvotes: 0

Necrolis
Necrolis

Reputation: 26181

you can do this non-recursively using something like this:

std::string Dec2Bin(int nValue, bool bReverse = false)
{
    std::string sBin;  
    while(nValue != 0)
    {
       sBin += (nValue & 1) ? '1' : '0';
       nValue >>= 1;
    }

    if(!bReverse)        
        std::reverse(sBin.begin(),sBin.end());

    return sBin;
}

of course this isn't too architucture friendly, but it avoids cout, just incase your not using a console. it also outputs in any bit ordering.

Upvotes: 2

Michael Buen
Michael Buen

Reputation: 39483

offering the iterative approach (pardon the #defines (but i'm quite sure they will be compiled to the expression's value), i don't quite remember predefined macro/constants in C):

#define INT_ARCH 32
#define ARCH_SHIFTABLE (INT_ARCH - 1)
#define ARCH_MAX_INT 1 << ARCH_SHIFTABLE

void dec_to_bin(int decimal)
{                
    int shifter = ARCH_MAX_INT;

    for(; shifter > 0; shifter >>= 1)
        cout << (decimal & shifter);        
}

Upvotes: 0

nc3b
nc3b

Reputation: 16270

You can use itoa if it's available on your compiler. Just remember it's not standard and if you need a standard method you're better off using the other solutions posted.

Upvotes: 1

Il-Bhima
Il-Bhima

Reputation: 10880

If you want to print it, just use this code here. If you want to return a string, instead of using cout, append to a C++ string instead.

Upvotes: 0

Nullw0rm
Nullw0rm

Reputation: 913

A simple function could be defined such as this:

void binary(int decimal) {
   int remainder;

   if(decimal <= 1) {
       std::cout << decimal;
       return;
   }
   remainder = decimal % 2;
   binary(decimal >> 1);    
   std::cout << remainder;
}

Although there are many other resources on the web on how to do this..

A noteworthy question for efficiency of it here, as you may want more than just that: Efficiently convert between Hex, Binary, and Decimal in C/C++

Upvotes: 3

Related Questions