C# convert byte[] containing a c-style string to string - NOT Encoding.GetString(byte[]) -


stupid me tries convert byte-array received external source not unter control string. (and yes, know encoding.getstring(byte[]).

what have far:

void myfunc() {     byte[] rawdata = new byte[ 128 ];      for( int = 0; < rawdata.length; ++i )     {         rawdata[ ] = 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 strings contain hello part lot of \0's afterwards - not thing expected. output 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 way geive me string "hello" ?

i did goolge,but got encoding.getstring(byte[]) ...

edit: creatin of byte array outside scope! part of larger, c-style struct. , there no leading length of string. hoping there iss ome built in way tdo , did not have find first \o , tehn convert knowing length....

edit here used in end:

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 ); } 

just find first 0:

    int len = array.indexof(rawdata, (byte)0); // maybe bounds check     string asstring = encoding.utf8.getstring(rawdata, 0, len); 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -