itoa将base 2中的整数转换为字符串的任何替代方法?

时间:2014-05-30 02:18:13

标签: c++ itoa

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

2 个答案:

答案 0 :(得分:0)

您可以轻松编写自己的。

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以及许多其他替代方案。

答案 1 :(得分:0)

对于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;
}
相关问题