2

How can I convert a BYTE array in a CString in MFC?

4 Answers 4

5

Try this - for eg: - If 'x' is your Byte array then -

BYTE x[5]; 
x[0] = 'A'; 
x[1] = 0; 
x[2] = 'B'; 
x[3] = 'C'; 
x[4] = 0; 

CString str( (LPCSTR) &x, sizeof(x) ); 
Sign up to request clarification or add additional context in comments.

Comments

0
BYTE x[5]; x[0] = 'A'; x[1] = 'B'; x[2] = 'C'; x[3] = 'D'; x[4] = '0';

CString str = TEXT("");
CString s;
for(int i=0;i<5;i++)
{
    str.Format(L"%C",x[i]);
    s += str;
}

AfxMessageBox(s);

Comments

0

This solution works for both array of char or wchar

CString ByteArrayToCString(BYTE* arr, int length)
{
    if (!arr || length == 0)
    {
        return _T("");
    }

    CString str(reinterpret_cast<TCHAR*>(arr), length / sizeof(TCHAR));
    return str;
}

Comments

-2
BYTE packet[IN_PACKET_SIZE];
CString Text;
Text.Format((LPCWSTR)L"%d hours \t%d minutes \t%d seconds \t%d °C", packet[0], packet[1], packet[2], packet[3]);

2 Comments

Please also add some explanation to your answer.
Code-only answers are discouraged. Please click on edit and add some words summarising how your code addresses the question, or perhaps explain how your answer differs from the previous answer/answers. From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.