4

Can anybody give an example of c++ code that can easily convert a decimal value to binary and a binary value to decimal please?

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
Jony
  • 6,694
  • 20
  • 61
  • 71
  • In what format? Strings? Numerical types don't care about base, since they're all stored as binary data regardless... – Amber Mar 30 '10 at 20:04
  • 8
    Where'd the `"guru"` part in the name come from? ;-) – mjv Mar 30 '10 at 20:04
  • it can be anything int...String...i was looking for smallest and efficient code. – Jony Mar 30 '10 at 20:06
  • 1
    Likely duplicate: http://stackoverflow.com/questions/819487/efficiently-convert-between-hex-binary-and-decimal-in-c-c – mjv Mar 30 '10 at 20:06
  • The question doesn't make sense if it's an `int`, Codeguru. – Amber Mar 30 '10 at 20:07
  • @Dav: I'm guessing Codeguru actually means that the input could be anything, but the output should be a string? – Cascabel Mar 30 '10 at 20:08
  • 1
    @mjv: +1. My handle used to be UfcChampion9YearsRunning... –  Mar 30 '10 at 20:08
  • @MaxGuernseyIII: LOL. Assuming UFC is as in "Ultimate Fighting", at least nobody would dare make fun of your handle... I couldn't resist here with our OP, a guru who doesn't find his way around google or a good reference book ;-) – mjv Mar 30 '10 at 20:28

4 Answers4

24

Well, your question is really vague, so this answer is the same.

string DecToBin(int number)
{
    if ( number == 0 ) return "0";
    if ( number == 1 ) return "1";

    if ( number % 2 == 0 )
        return DecToBin(number / 2) + "0";
    else
        return DecToBin(number / 2) + "1";
}

int BinToDec(string number)
{
    int result = 0, pow = 1;
    for ( int i = number.length() - 1; i >= 0; --i, pow <<= 1 )
        result += (number[i] - '0') * pow;

    return result;
}

You should check for overflow and do input validation of course.

x << 1 == x * 2

Here's a way to convert to binary that uses a more "programming-like" approach rather than a "math-like" approach, for lack of a better description (the two are actually identical though, since this one just replaces divisions by right shifts, modulo by a bitwise and, recursion with a loop. It's kind of another way of thinking about it though, since this makes it obvious you are extracting the individual bits).

string DecToBin2(int number)
{
    string result = "";

    do
    {
        if ( (number & 1) == 0 )
            result += "0";
        else
            result += "1";

        number >>= 1;
    } while ( number );

    reverse(result.begin(), result.end());
    return result;
}

And here is how to do the conversion on paper:

  1. Decimal to binary
  2. Binary to decimal
IVlad
  • 43,099
  • 13
  • 111
  • 179
  • What if we want to have a fixed length of binary number? For example, if we would like to have an 8 bit representation, then `1` has to be returned as `00000001`. – Rasoul Sep 08 '13 at 16:10
  • @Rasoul - then just add leading zeros until you get your desired length. Some programming languages provide methods to do this out of the box. – IVlad Sep 08 '13 at 16:13
2
//The shortest solution to convert dec to bin in c++

void dec2bin(int a) {
    if(a!=0) dec2bin(a/2);
    if(a!=0) cout<<a%2;
}
int main() {
    int a;
    cout<<"Enter the number: "<<endl;
    cin>>a;
    dec2bin(a);
    return 0;

}

NoriMax
  • 21
  • 1
2

strtol will convert a binary string like "011101" to an internal value (which will normally be stored in binary as well, but you don't need to worry much about that). A normal conversion (e.g. operator<< with std:cout) will give the same value in decimal.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

I assume you want a string to binary conversion?

template<typename T> T stringTo( const std::string& s )
   {
      std::istringstream iss(s);
      T x;
      iss >> x;
      return x;
   };

template<typename T> inline std::string toString( const T& x )
   {
      std::ostringstream o;
      o << x;
      return o.str();
   }

use these like this:

int x = 32;
std:string decimal = toString<int>(x);
int y = stringTo<int>(decimal);
Jay
  • 13,803
  • 4
  • 42
  • 69