Is there a way to convert a number represented as a string into its binary equivalent?

The shell of the desired code:

#include <iostream>
#include <string>

std::string str_to_bin(const std::string& str)
{
    //...
}

int main()
{
    std::string str = "123";

    std::cout << str_to_bin(str); //would print 1111011
}

The name of the question says it all. I was stuck on this for a while. Is there a solution for this in STL? Or something simple that I am missing? If not, how would I do it? Maybe a direction you could turn me to? In addition, speed is of great importance.

EDIT: The number can be of any size (larger than long long), which is why std::stoithey std::bitset<>are located outside the table.

+4
source share
2 answers

You can do this using GMP (GNU multithreading) . Something like that:

#include <gmpxx.h>

std::string str_to_bin(const std::string& str)
{
    mpz_class bignum;
    int rc = bignum.set_str(str, 10);
    if (rc != 0)
        throw std::invalid_argument("bad number: " + str);

    return bignum.get_str(2);
}

Or using the traditional C API:

#include <gmp.h>

std::string str_to_bin(const std::string& str)
{
  mpz_t bignum;
  int rc = mpz_set_str(bignum, str.c_str(), 10);
  if (rc != 0)
    throw std::invalid_argument("bad number: " + str);

  char* rawstr = mpz_get_str(nullptr, 2, bignum);
  std::string result(rawstr);
  free(rawstr);
  return result;
}
+3

, , . ( )

  • , , .
  • , . ( , )

1:

stoi(). , , .

std::string numberstr = "123";
int numberint = std::stoi(numberstr);
std::cout << numberint << "\n";

.

2:

  • 10 () 2 ().
  • 2.
  • .
  • , .
  • , 1, .
  • ! .

  • (, , ), , , , true, .

  • .

:

std::string str_to_bin(const std::string& str)
{
    std::string binarystr = ""; // Output string

    int remainder;
    int numberint = std::stoi(str);
    bool flagnegative = false;
    // If negative number, beginning of binary equivalent is 1
    if (numberint < 0)
    {
        numberint = abs(numberint);
        flagnegative = true;
    }
    // If number is 0, don't perform conversion simply return 0
    if (numberint == 0)
    {
        binarystr = "0";
        return binarystr;
    }
    std::cout << numberint << "\n";

    while (numberint != 1)
    {
        remainder = numberint % 2;
        numberint /= 2;
        std::ostringstream convert; // stream used for the conversion
        convert << remainder;      // insert the textual representation of 'remainder' in the characters in the stream
        binarystr += convert.str();
    }
    std::ostringstream final;
    final << numberint;         // To insert the last (or rather first once reversed) binary number
    binarystr += final.str();
    if (flagnegative == true)
        binarystr += "-";
    std::reverse(binarystr.begin(), binarystr.end());
    return binarystr;
}

STL , , , , , .

, , ! , , . - .

Anywho, , ! .

0

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


All Articles