In this thread some one commented that the following code should only be used in 'toy' projects. Unfortunately he hasn't come back to say why it's not of production quality so I was hoping some one in the community may be able to either assure me the code is ok (because I quite like it) or identify what is wrong.
template< class T1, class T2>
void hexascii( T1& out, const T2& in )
{
out.resize( in.size() * 2 );
const char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
T1::iterator outit = out.begin();
for( T2::const_iterator it = in.begin(); it != in.end(); ++it )
{
*outit++ = hexDigits[*it >> 4];
*outit++ = hexDigits[*it & 0xF];
}
}
template<class T1, class T2>
void asciihex( T1& out, const T2& in )
{
size_t size = in.size;
assert( !(size % 2) );
out.resize( size / 2 );
T1::iterator outit = out.begin();
for( T2::const_iterator it = in.begin(); it != in.end(); it += 2, ++outit )
{
*outit = ((( (*it > '9' ? *it - 0x07 : *it) - 0x30) << 4) & 0x00f0) +
(((*(it+1) > '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f);
}
}
Edit: Thanks for your help guys, you've made some big improvements. I've written functions in the two suggested styles from your answers. Some rough testing suggests the second method is marginally faster than the first, but IMO this is outweighed by the improved readability of the first.
template<class T1>
void asciihex2( T1& out, const std::string& in )
{
dassert( sizeof(T1::value_type)==1 );
size_t size = in.size();
assert( !(size % 2) );
out.resize( size / 2 );
T1::iterator outit = out.begin();
for( size_t i = 0; i < in.size(); i += 2 )
{
int tmp;
sscanf( in.c_str() + i, "%02X", &tmp );
*outit++ = tmp;
}
}
template<class T1>
void asciihex3( T1& out, const std::string& in )
{
dassert( sizeof(T1::value_type)==1 );
size_t size = in.size();
assert( !(size % 2) );
out.resize( size / 2 );
T1::iterator outit = out.begin();
const char hexDigits[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
for( std::string::const_iterator it = in.begin(); it != in.end(); it += 2, ++outit )
{
*outit = (hexDigits[(*it - 0x30) & 0x1f] << 4) +
hexDigits[((*(it+1) - 0x30) & 0x1f)];
}
}
Some of the assumptions surronding this code: 1: They are not intended as a generic, but are used in an anonymous name space to translate data for a specific class. 2: The templating is required as two separate container types are being used (one being std::vector, the other a similar byte array type container from a third party library. 3: The purpose is to be able to convert binary data of indeterminate length into strings and back again (0x1234abcd <-> "1234abcd") 4: assert traps errors in both debug and release modes 5: by the time these functions are called the size of the string will already have been checked, assert is used to terminate processing if something serious has gone wrong 6: It needs some commenting
Any other ideas appreciated.