0
Expensive,
I am doing a function for decimal to binary conversion, which is returned in a string. As C++ does not have StringBuffer
, I’m using the stringstream
. However, I always have build error when using the function write
of stringstream
. The code is this:
string toBin(int valor, int bits) {
int resto = -1, i = 0;
stringstream ss;
if (valor == 0) {
return "0";
}
while (valor > 0) {
resto = valor % 2;
valor = valor / 2;
ss.seekp(0);
ss.write(resto, i++);
}
return ss.str();
}
The intention is that with each rest found, I insert it in the first position of the stringstream, to form the binary. And the error found is:
"invalid Conversion from 'int' to 'const char*'
How could I solve this problem? Or is there a C++ library that already does the decimal to binary conversion?
Grateful!
Perfect answer! With bitset I won’t need to handle the amount of return bits. Thank you very much!
– Daniel Elias