c++ - 有没有办法将表示为字符串的数字转换为其二进制等价物?

标签 c++ c++11

所需代码的外壳:

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

问题标题说明了一切。我已经坚持了一段时间。在STL中有解决方案吗?还是我缺少的简单东西?如果没有,我将如何去做呢?也许你可以指出我的方向?另外,速度也很重要。

编辑: 数字可以是任意大小(也可以大于 long long),所以 std::stoistd::bitset<>不在讨论范围内。

最佳答案

您可以使用 GMP (GNU Multi-Precision) 来做到这一点.像这样:

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

或者使用传统的 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;
}

关于c++ - 有没有办法将表示为字符串的数字转换为其二进制等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381002/

相关文章:

c++ - 弗洛伊德-沃歇尔算法

C++11 模板函数 "implicity"将 bitset<N> 转换为 "unsigned long"

c++ - 不匹配 'operator <<' ?

python - 在 C++ 和 Python 程序之间共享数据的最快方法?

c++ - 使用 gcc 在 Linux 上运行线程构建 block (Intel TBB)

c++ - 为什么 C++17 中没有 std::future::then?

c++ - uninitialized_copy() 异常安全吗?

c++ - 函数 `feof` 总是返回 1

c++ - 使用 boost 信号而不是 qt

c++ - 使用可变参数模板进行类型推导和参数传递