first bytes of a string

  • Thread starter Thread starter Dirk Reske
  • Start date Start date
Dirk,

You can get the bytes from a string by calling the GetBytes method on
the encoding. If you want the bytes as represented in ASCII, you can do the
following:

// The byte array to encode into.
byte[] pbytBytes = new byte[4];

// Get the bytes in a string.
Encoding.ASCII.GetBytes("what is this",
0, // The character in the string to encode from.
4, // The number of characters to encode.
pbytBytes, // The byte array to encode into.
0 // The index in the byte array to begin writing to
);

Hope this helps.
 
Dirk Reske said:
how do I get the first e.g. 4 bytes of a string into a byte array?

Do you mean bytes, or do you mean characters? If you mean characters,
you could take a substring and then copy it to a char array:

char[] c = myString.Substring(0, 4).ToCharArray();
 
Back
Top