CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Hybrid View

  1. #1
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443

    MFC String: How to get the hexadecimal representation of a ... into a 'CString'?

    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:

    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"
    We also provide another solution that uses Standard C++ classes.


    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"

    Last edited by Andreas Masur; July 24th, 2005 at 06:42 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured