stupid me trying to convert a byte array received from an external source does not override my string control. (And yes, I know about Encoding.GetString(byte[]).
What I still have:
void myfunc()
{
byte[] rawData = new byte[ 128 ];
for( int i = 0; i < rawData.Length; ++i )
{
rawData[ i ] = 0;
}
rawData[ 0 ] = (byte)'H';
rawData[ 1 ] = (byte)'e';
rawData[ 2 ] = (byte)'l';
rawData[ 3 ] = (byte)'l';
rawData[ 4 ] = (byte)'o';
string asString = Encoding.UTF8.GetString( rawData, 0, rawData.Length );
string asRealString = Encoding.UTF8.GetString( rawData );
}
Both lines contain the Hello part, but also a lot \ 0 after - this is not what I expected. Exit the debugger: asRealString =
"Hello\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
Is there any way that can create me a string like "Hello"?
I went, but all I had was Encoding.GetString(byte[])...
. ! C-Style. .
, , , , , .., .
:
private static string convertCString( byte[] buffer, int maxLength, Encoding targetEncoding )
{
int length = 0;
int realMax = buffer.Length < maxLength ? buffer.Length : maxLength;
for(
; 0 != buffer[length] && length < realMax
; ++length )
{}
return targetEncoding.GetString( buffer, 0, length );
}