Decimal value in binary (and vice versa)

Can someone give an example of C ++ code that can easily convert a decimal value to binary and binary value to decimal number?

+3
source share
4 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 must check for overflow and perform input validation, of course.

x << 1 == x * 2

, " " , ", ", - ( , , . , , ).

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

:

+21

strtol "011101" ( , ). (, operator<< std:cout) .

+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;

}

+2

, ?

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();
   }

:

int x = 32;
std:string decimal = toString<int>(x);
int y = stringTo<int>(decimal);
+1

Source: https://habr.com/ru/post/1739198/


All Articles