any alternative of itoa converting integer in base 2 to string?

736 Views Asked by At

as we know itoa tries to convert an integer in any base but to char array which has fix size, I am trying to find an alternative which can do the same work but convert to string with base 2 in c++.

2

There are 2 best solutions below

0
On

You can easily write your own.

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 was taken from this website, along with many other alternatives.

0
On

For C++11, you can use bitset and to_string.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    // your code goes here
    cout << bitset<4>(10).to_string() << endl;
    return 0;
}