Re: convert BYTE array into a CString
"Mirs" <mirs@giron.com> ha scritto nel messaggio
news:el4%23j3gWJHA.1328@TK2MSFTNGP02.phx.gbl...
I need to convert BYTE array ( like BYTE buffer[8] ) into a CString object.
Is it possible and how?
To add to what Dave correctly wrote, if your purpose is instead to build a
string containing the bytes stored in the array, printed in hex, you could
use code like this:
<code>
// Returns a string containing input bytes (stored in array)
// printed in hex.
// Each byte is separated by the next one using a space.
CString FormatByteArrayToString(const BYTE * pb, int count)
{
// Check input parameters
ASSERT(pb != NULL);
ASSERT(count > 0);
// This string will store the bytes in hex
CString result;
// Print 1st byte
result.Format(_T("%02X"), pb[0]);
// For each byte from 2nd to last:
for (int i = 1; i < count; i++)
{
// Format current byte in hex, and separate it
// by previous one using a space
CString hexByte;
hexByte.Format(_T(" %02X"), pb[i]);
// Add current byte final string
result += hexByte;
}
return result;
}
inline CString FormatByteArrayToString(const std::vector<BYTE> & byteArray)
{
return FormatByteArrayToString(&byteArray[0], byteArray.size());
}
</code>
The above functions can be used like this:
<code>
std::vector<BYTE> data;
data.push_back(3);
data.push_back(10);
data.push_back(0);
data.push_back(15);
CString result = FormatByteArrayToString(data);
MessageBox(NULL, result, _T("Bytes in the array:"), MB_OK);
</code>
Giovanni