Converting a String to Byte Array

It’s easy enough to use System.Text.UnicodeEncoding.Unicode.GetBytes() to do this kind of conversion but problems could occur when you have invisible/control characters in the string. A better approach would be to first convert the string to a character array then to byte array:


private static byte[] StringToBytes(string str)
{
  Converter conv = new Converter((c) => (byte)c);
  Array.ConvertAll(str.ToCharArray(), conv);
}

發表迴響

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

連結到 %s

Follow

Get every new post delivered to your Inbox.