Click here to Skip to main content
15,893,722 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tried to convert a CString To BYTE* and "BYTE* to CByteArray" in MFC,The CString Has Been Converted To BYTE*. But I'm not able to Convert The Entire Byte* To CByteArray It Returns Partial Data With Some Garbage Values. I Described My Actual Problem Here...

What I have tried:

CString csData =_T("someData");

BYTE *pByteArray = (PBYTE)(LPCTSTR)csData.GetBuffer();

CString str;
str=LPTSTR(pByteArray);
AfxMessageBox(str); //returns "someData" 

CByteArray arrByte2;

arrByte2.SetSize(csData.GetLength()+1);

memcpy(arrByte2.GetData(), pByteArray, csData.GetLength()+1);

CString text((LPTSTR)arrByte2.GetData(),arrByte2.GetSize());
CStringA result(text);
AfxMessageBox(text);//returns "some﵄﷽꯽ꮫꮫ"
Posted
Updated 24-May-18 20:55pm
v2

A CString is a sequence of TCHAR characters. A TCHAR is a char or a wchar_t depending on the project character set setting (ANSI/multi-byte or Unicode).

You can cast the pointer to the data in the CString to BYTE*:
C++
const BYTE *pByte = reinterpret_cast<const BYTE*>(str.GetString());
Note that I have used C++ casting here and use const because the CString::GetString() return type is LPCTSTR. If you really need a non const pointer (want to modify the CString) you can use CString::GetBuffer() but then you have to call CString::ReleaseBuffer() afterwards.

If you have a Unicode build, the number of characters in the string is not identical to the number of bytes. You have to take that into account when copying to the byte array. Then there is also no need for a BYTE* pointer variable:
C++
CByteArray arrByte2;
// The number of bytes in the CString including the terminating NULL bytes
size_t byteSize = (str.GetLength() + 1) * sizeof (TCHAR);
arrByte2.SetSize(byteSize);
// No need to cast here because the memcpy() parameters are of type void*
memcpy(arrByte2.GetData(), str.GetString(), byteSize);
Now the byte array contains all the bytes from the string including the terminating NULL bytes and can be assigned back to a CString:
C++
CString text(reinterpret_cast<LPCTSTR>(arrByte2.GetData()), arrByte2.GetSize() / sizeof(TCHAR));
Note that the number of characters has to be calculated now by dividing by the size of a character. It would be also not necessary to have a terminating NULL byte in the array here because the CString constructors accepting a length parameter will append that.
 
Share this answer
 
Because you use UNICODE the string has 2 byte size and so your buffer is to small. So you double the buffer siz of the CByteArray.
C++
arrByte2.SetSize(2*(csData.GetLength()+1));

BTW: You have watched it correctly, but didnt understand it as error hint ;-)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900