I have a matching pair of static functions in a utility class that I use to convert between binary data (unsigned characters) and it\'s string representation (a-f and 0-9). They
I would rewrite the code to actually use C++ facilities (haven't tested it really, just an idea):
std::vector string_to_binary(const std::string& source)
{
static int nibbles[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15 };
std::vector retval;
for (std::string::const_iterator it = source.begin(); it < source.end(); it += 2) {
unsigned char v = 0;
if (std::isxdigit(*it))
v = nibbles[std::toupper(*it) - '0'] << 4;
if (it + 1 < source.end() && std::isxdigit(*(it + 1)))
v += nibbles[std::toupper(*(it + 1)) - '0'];
retval.push_back(v);
}
return retval;
}
std::string binary_to_string(const std::vector& source)
{
static char syms[] = "0123456789ABCDEF";
std::stringstream ss;
for (std::vector::const_iterator it = source.begin(); it != source.end(); it++)
ss << syms[((*it >> 4) & 0xf)] << syms[*it & 0xf];
return ss.str();
}