Re: Conversion of byte array to cstring
"AliR (VC++ MVP)" <AliR@online.nospam> ha scritto nel messaggio
news:SFhzi.4581$LL7.4217@nlpi069.nbdc.sbc.com...
What kind of conversion are we talking about, what is the byte array
representing? Does the byte array have 0 anywhere in it?
Here is one way
CString Buffer;
for (int i = 0; i < Array.Length();i++)
{
Buffer += (TCHAR)Array.GetAt(i);
}
Hello Alir,
I don't want to be picky, but I don't like very much the above TCHAR cast...
I think that the above code could be OK *without the TCHAR cast*, if Array
stores BYTEs, which are the ANSI characters to be put in the CString.
But if the input array stores bytes for Unicode UTF-16 strings, I think that
it would not be correct.
I think that a code like the following could be OK, with two separate
branches for ANSI and Unicode (UTF-16):
<code>
///////////////////////////////////////////////////////////
// An array storing BYTEs
///////////////////////////////////////////////////////////
typedef std::vector< BYTE > ByteArray;
///////////////////////////////////////////////////////////
// Build a ANSI string from characters stored into a
// byte array
///////////////////////////////////////////////////////////
CStringA BuildAnsiString( const ByteArray & chars )
{
if ( chars.empty() )
return "";
const int charsCount = static_cast<int>( chars.size() );
CStringA str( ' ', charsCount );
for ( int i = 0; i < charsCount; i++ )
{
str.SetAt( i, chars[ i ] );
}
return str;
}
///////////////////////////////////////////////////////////
// Build a Unicode UTF-16 string from characters stored
// into a byte array
///////////////////////////////////////////////////////////
CStringW BuildUnicodeString( const ByteArray & chars )
{
if ( chars.empty() )
return L"";
// Unicode chars count
const int charsCount = static_cast<int>( chars.size() ) / 2;
CStringW str( ' ', charsCount );
const BYTE * pBytes = &chars[0];
for ( int i = 0; i < charsCount; i++ )
{
// Build the Unicode UTF-16 code-point
WCHAR wch = MAKEWORD( *pBytes, *(pBytes+1) );
// Point to next WCHAR in source array
pBytes += 2;
// Update string character
str.SetAt( i, wch );
}
return str;
}
//
// TEST
//
void Test()
{
//
// ANSI Test
//
ByteArray ansiChars;
ansiChars.push_back( 0x48 ); // H
ansiChars.push_back( 0x49 ); // I
CStringA strAnsi = BuildAnsiString( ansiChars );
CA2W s( strAnsi );
AfxMessageBox( s );
//
// Unicode Test
//
ByteArray charsUnicode;
charsUnicode.push_back( 0xB1 ); // alpha
charsUnicode.push_back( 0x03 );
charsUnicode.push_back( 0xB4 ); // delta
charsUnicode.push_back( 0x03 );
CStringW strUnicode = BuildUnicodeString( charsUnicode );
AfxMessageBox( strUnicode );
}
</code>
Maybe the OP was not very clear about the content of his byte-array...
Giovanni