Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal to binary (and vice-versa)

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

like image 294
Jony Avatar asked Nov 27 '22 12:11

Jony


2 Answers

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
like image 168
IVlad Avatar answered Dec 05 '22 02:12

IVlad


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.

like image 25
Jerry Coffin Avatar answered Dec 05 '22 01:12

Jerry Coffin