Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Need help converting CString to hex

FlackFlack Member Posts: 88
Hello,

Lets say I have a CString m_strMessage = "TESTING" in my MFC app.

Now, what I would like to do is convert each char in TESTING to its hex value and store those values.

For example, TESTING would give me T=54 E=45 S=53 T=54 I=49 N=4E G=47, where each letter was changed to its hex value (as written in the ascii chart).

Is there a way I can go char by char and do the conversion?

Thanx for the help,
-Flack

Comments

  • weiccoweicco Member Posts: 950
    [code]
    LPSTR p = m_strMessage.GetBuffer(1);
    int len = m_strMessage.GetLength();

    for (int n = 0 ; n < len ; n++) {
    TCHAR tmp[4] = { 0 };
    _stprintf(tmp, TEXT("%02x "), p[n]);

    m_strOutput += tmp;
    }

    m_strMessage.ReleaseBuffer();
    [/code]

    : Hello,
    :
    : Lets say I have a CString m_strMessage = "TESTING" in my MFC app.
    :
    : Now, what I would like to do is convert each char in TESTING to its hex value and store those values.
    :
    : For example, TESTING would give me T=54 E=45 S=53 T=54 I=49 N=4E G=47, where each letter was changed to its hex value (as written in the ascii chart).
    :
    : Is there a way I can go char by char and do the conversion?
    :
    : Thanx for the help,
    : -Flack
    :

  • slicer69slicer69 Member Posts: 272
    I think that C/C++ will let you print out hex values for integers.
    I believe you can do this with the printf() function, using the
    string contant "%x". Look it up, just to be sure.

    So let's say that you have a string:
    char my_string[] = "Testing";

    And you want to print out the hex value of each char, you might try this:

    char my_string[] = "Testing";
    int index;

    for (index = 0; index <= strlen(my_string); index++)
    printf("%x
    ", my_string[index]);


    Hope that helps.

    : Hello,
    :
    : Lets say I have a CString m_strMessage = "TESTING" in my MFC app.
    :
    : Now, what I would like to do is convert each char in TESTING to its hex value and store those values.
    :
    : For example, TESTING would give me T=54 E=45 S=53 T=54 I=49 N=4E G=47, where each letter was changed to its hex value (as written in the ascii chart).
    :
    : Is there a way I can go char by char and do the conversion?
    :
    : Thanx for the help,
    : -Flack
    :

  • data4usedata4use Member Posts: 1
    [code]
    char* ToHex(char Character)
    {

    char* cp_tmp = (char*)malloc(2);
    int hxc = 0; // HeX Code

    sprintf(cp_tmp, "%02X", Character);

    return cp_tmp;

    }
    [/code]
  • AsmGuru62AsmGuru62 Member Posts: 6,519
    [color=Blue]sprintf will store 3 characters into that 2 bytes buffer! You need [italic]malloc(3)[/italic] for the properly functioning code.[/color]
Sign In or Register to comment.