Search
Close this search box.

How to convert a string to a byte array and convert a byte array to a string

This is something I wanted to do a while ago.. and ended up coding manually (duh!) like this:

string myString = "a test string";
byte[] myByteArray = new byte[myString.Length];
int i = 0;
foreach (char c in InStr.ToCharArray()) {
  myByteArray[i] = (byte)c;
  i++;
}

Then some kind soul (thanks Michael) mentioned the Encoding class <slaps forehead>…

System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] myByteArray = enc.GetBytes("a text string);
string myString = enc.GetString(myByteArray );

Simple eh 😉

Tim

This article is part of the GWB Archives. Original Author: A Complete Load of Bollocks

Related Posts