【问题标题】:any alternative of itoa converting integer in base 2 to string?itoa 将基数 2 中的整数转换为字符串的任何替代方法?
【发布时间】:2014-05-30 02:18:12
【问题描述】:

正如我们所知,itoa 尝试将任何基数的整数转换为具有固定大小的 char 数组,我正在尝试找到一种替代方法,它可以完成相同的工作,但在 c++ 中转换为以 2 为基数的字符串。

【问题讨论】:

标签: c++ itoa


【解决方案1】:

您可以轻松编写自己的代码。

void my_itoa(int value, std::string& buf, int base){

    int i = 30;

    buf = "";

    for(; value && i ; --i, value /= base) buf = "0123456789abcdef"[value % base] + buf;

}

这取自this website,以及许多其他替代方案。

【讨论】:

    【解决方案2】:

    对于 C++11,您可以使用 bitsetto_string

    #include <iostream>
    #include <bitset>
    using namespace std;
    
    int main() {
        // your code goes here
        cout << bitset<4>(10).to_string() << endl;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 2011-07-31
      • 2019-02-18
      • 1970-01-01
      • 2013-06-12
      • 2016-09-19
      • 2013-11-06
      相关资源
      最近更新 更多