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:
We also provide another solution that uses Standard C++ classes.Code: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"
Strings
Code:CString StringToHexString(CString cs) { CString ret, tmp; for(int i=0; i<cs.GetLength(); ++i) { unsigned char c = cs[i]; tmp.Format(" %02hX", c); ret+=tmp; } return ret; } AfxMessageBox(StringToHexString("Hello"), MB_OK, 0); // produces a message box containing "48 65 6C 6C 6F"




Reply With Quote