Click to See Complete Forum and Search --> : MFC String: How to get the hexadecimal representation of a ... into a 'CString'?


Gabriel Fleseriu
February 14th, 2003, 04:00 AM
Q: How to get the hexadecimal representation of a ... into a 'CString'?

A: There are two common scenarios: wanting a string containing the hexadecimal representation of some built-in type variable, like an 'int' or a 'float' or wanting the hexadecimal representation of every byte from a string.

Built-in types

The following template function can be used for built-in types:


template <class T>
CString VariableToHexString(T t)
{
CString ret, tmp;
for(int i = sizeof(T)-1; i>=0; --i)
{
unsigned char c = reinterpret_cast<unsigned char*>(&t)[i];
tmp.Format("%02hX", c);
ret+=tmp;
}
return ret;
}

AfxMessageBox(VariableToHexString<int>(12345678),
MB_OK,
0);
// produces a message box containing "00 BC 61 4E"

We also provide another <A HREF="http://www.codeguru.com/forum/showthread.php?s=&threadid=231054">solution</a> that uses Standard C++ classes.


Strings


CString StringToHexString(CString cs)
{
CString ret, tmp;
for(int i=0; i&lt;cs.GetLength(); ++i)
{
unsigned char c = cs[i];
tmp.Format(&quot; %02hX&quot;, c);
ret+=tmp;
}
return ret;
}

AfxMessageBox(StringToHexString("Hello"), MB_OK, 0);
// produces a message box containing "48 65 6C 6C 6F"

<br><br>