E
Eric Lilja
Hi, I need a function that expects a const std::string& containing the
visual representation of a number in binary format. It should then output
this number in groups of four bits separated by a space. If the length of
the string is not divisable by four (normally, it should receive 8-bit
numbers (that is, strings of length 8), it should output the number as-is,
no grouping). I came up with:
void
output_binary_string(ostream& os, const string& binary_string)
{
/* If the length of the string (i.e., the number of bits in *
* the binary number), isn't divisable by four, simply output *
* the entire string and return. */
if(binary_string.length() % 4)
{
os << binary_string;
return;
}
string::size_type index = 0;
for(string::size_type i = 0; i < binary_string.length() / 4; ++i)
{
for(int j = 0; j < 4; j++)
{
os << binary_string[index++];
}
os << ' ';
}
}
Now, what if I want to use this function in a cout-statement? Do I have to
create a class or struct then and make my function the overloaded operator<<
for that class/struct?
Right now I do:
cout << "binary_representation: ";
output_binary_string(cout, s);
cout << endl;
I would like to be able to cout << "binary representation: " <<
output_binary_string(cout, s) << endl;
Thanks for any replies
visual representation of a number in binary format. It should then output
this number in groups of four bits separated by a space. If the length of
the string is not divisable by four (normally, it should receive 8-bit
numbers (that is, strings of length 8), it should output the number as-is,
no grouping). I came up with:
void
output_binary_string(ostream& os, const string& binary_string)
{
/* If the length of the string (i.e., the number of bits in *
* the binary number), isn't divisable by four, simply output *
* the entire string and return. */
if(binary_string.length() % 4)
{
os << binary_string;
return;
}
string::size_type index = 0;
for(string::size_type i = 0; i < binary_string.length() / 4; ++i)
{
for(int j = 0; j < 4; j++)
{
os << binary_string[index++];
}
os << ' ';
}
}
Now, what if I want to use this function in a cout-statement? Do I have to
create a class or struct then and make my function the overloaded operator<<
for that class/struct?
Right now I do:
cout << "binary_representation: ";
output_binary_string(cout, s);
cout << endl;
I would like to be able to cout << "binary representation: " <<
output_binary_string(cout, s) << endl;
Thanks for any replies