No, not good at all. First of all, it does not return anything, does not even allow the user to put data in a string. Second of all, the implementation is way too inefficient, compared even to the simplest reasonable implementation. Finally, the function could be generic, otherwise how would yo reuse the code for
long int,
unsigned int, and so on? You could use a C++ template.
So first, you need to have a function profile like (let's forget templates for now).
std::string ToBinary(int value);
or, to use just the null-terminated strings, in C style:
void ToBinary(char* string, int value);
In the second case, the user needs to be held responsible for providing a reference to a string which provides enough room for all the binary digits, according to the size of data.
Finally, learn a recipe for extracting separate bits form data.
First, use binary '<<' and '&' operators. If you need to extract N-th byte, where N is the integer index of the bit, counted from least-significant bit #0 (rightmost) toward a most-significant bit, first get the mask equals to
1 << N
. If you then AND this mask with your value, you will get either 0 value or not:
if (value & (1 << N) == 0)
else
(Put real code instead of my comments.)
Using these ideas, please write the whole implementation.
See also:
http://www.cplusplus.com/reference/string/string[
^],
http://www.learncpp.com/cpp-tutorial/38-bitwise-operators[
^].
—SA