byte[] -> string

  • Thread starter Thread starter Andrea
  • Start date Start date
Andrea said:
how can I convert a byte[] to a string ?
Any idea?

Andrea

How are the characters encoded in the byte array? You need to examine the
System.Text.Encoding class and its related classes:
System.Text.ASCIIEncoding, System.Text.UnicodeEncoding. Here's a basic
example, if the byte array is ASCII:

System.Text.ASCIIEncoding AE = new System.Text.ASCIIEncoding();
byte[] ByteArray = { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116,
114, 105, 110, 103, 46 };
char[] CharArray = AE.GetChars(ByteArray);
string s = new string(CharArray);
MessageBox.Show(s);

Erik
 
Erik Frey said:
Andrea said:
how can I convert a byte[] to a string ?
Any idea?

Andrea

How are the characters encoded in the byte array? You need to examine the
System.Text.Encoding class and its related classes:
System.Text.ASCIIEncoding, System.Text.UnicodeEncoding. Here's a basic
example, if the byte array is ASCII:

System.Text.ASCIIEncoding AE = new System.Text.ASCIIEncoding();
byte[] ByteArray = { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116,
114, 105, 110, 103, 46 };
char[] CharArray = AE.GetChars(ByteArray);
string s = new string(CharArray);
MessageBox.Show(s);

Or, slightly more simply:

MessageBox.Show (Encoding.ASCII.GetString(bytes));

There's no need to create a new ASCIIEncoding, or to get a character
array and then create a string from that.
 
Or, slightly more simply:
MessageBox.Show (Encoding.ASCII.GetString(bytes));

There's no need to create a new ASCIIEncoding, or to get a character
array and then create a string from that.

That's what I get for cutting and pasting from MSDN :)

Erik
 
Erik Frey said:
That's what I get for cutting and pasting from MSDN :)

Could you let me know which MSDN page it is? I'm more than happy to
write an email suggesting a change...
 
Back
Top