how to convert a char array(byte[]) to a string variable?

D

David

Hi,

how to convert a char array(byte[]) to a string variable?

byte[] buffer;
string strTest;

/*the blow codes all get type of 'buffer': System.Byte[]!
strTest = buffer.ToString()
strTest = System.Convert.ToString(buffer)
*/

Thanks.
 
P

Patrick Smacchia

Depends on how your string is encoded in the byte[], is it UTF8, ASCII...?
Use the classes derived from the System.Text.Encoding class such as
System.Text.UTF8Encoding.

class Program {
static void Main() {
System.Text.Encoding utf = new System.Text.UTF8Encoding();
string str = "hello";
byte[] bin = utf.GetBytes(str);
string strCopy = utf.GetString(bin);
}
}

Patrick Smacchia
MVP.NET
Author of Practical .NET2 and C#2 http://www.PracticalDOT.NET
Author of NDepend: http://www.NDepend.com
 
J

Jon Skeet [C# MVP]

David said:
how to convert a char array(byte[]) to a string variable?

byte[] buffer;
string strTest;

/*the blow codes all get type of 'buffer': System.Byte[]!
strTest = buffer.ToString()
strTest = System.Convert.ToString(buffer)
*/

Aside from Patrick's answer, your first sentence reveals a
misunderstanding. A char array is *not* a byte[]. A byte[] is a byte
array, and a char[] is a char array. Chars are 16 bits in C#, always.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top