YASQ - Proper way to convert byte[] <--> string

Steve Teale steve.teale at britseyeview.com
Thu Jul 12 01:27:12 PDT 2007


Frits van Bommel Wrote:

> Steve Teale wrote:
> > I have a byte[] A that contains an AJP13 packet, presumably including UTF8 strings.  I need to extract such strings and to place strings in such a buffer.  I'm using:
> > 

> > string s = A[n .. m].dup;  // n and m from prefixed string length/position
> > return s;
> > 
> > to get strings, and
> 
> That should work, and be optimal unless you can be sure the A array 
> doesn't change while you still need the string (in which case the .dup 
> is unnecessary).
> 
> > byte[] ba = cast(byte[]) s;
> > A[n .. n+ba.length] = ba[0 .. $].dup;
> > 
> > to put them.  Are these a) sensible, b) optimal?
> 
> This one should work as well, but isn't optimal; the .dup is 
> unnecessary. This should be equivalent but more efficient:
> ---
> A[n .. n+s.length] = cast(byte[]) s;
> ---

Can I use n+s.length?  In my experimentation i noticed that a UTF8 string containing a character using a two-byte representation definitely had an s.length of the number of characters, which was one less than the number of bytes.



More information about the Digitalmars-d mailing list