As suggested, use the (generic-text variant of) strtol:
void StrToByte2(LPCTSTR str, BYTE * dest)
{
LONG u16 = _tcstol( str, NULL, 16);
dest[0] = (BYTE) (u16 >> 8);
dest[1] = (BYTE) (u16);
}
or at least, write a sensible hand-crafted one. Try
void StrToByte2Alt(LPCTSTR str, BYTE dest[])
{
for (size_t b=0; b<2; ++b)
{
dest[b] = 0;
for (size_t nb=0; nb<2; nb++)
{
dest[b] <<= 4;
TCHAR tc = str[2*b+nb];
if ( tc >= _T('0') && tc <= _T('9') )
dest[b] |= tc - _T('0');
else if ( tc >= _T('A') && tc <= _T('F') )
dest[b] |= tc - _T('A') + 10;
else if ( tc >= _T('a') && tc <= _T('f') )
dest[b] |= tc - _T('a') + 10;
else
{ }
}
}
}
or, using
C++
streams:
#ifdef UNICODE
typedef std::wistringstream InputStringStream;
#else
typedef std::istringstream InputStringStream;
#endif // UNICODE
BOOL strtobyte2(LPCTSTR str, std::array<BYTE, 2> & b)
{
UINT16 u16;
InputStringStream iss(str);
iss >> hex >> u16;
if ( ! iss) return FALSE;
b[0] = static_cast<BYTE>(u16 >> 8);
b[1] = static_cast<BYTE>(u16);
return TRUE;
}