Friday, June 19, 2009

C# How to convert byte arry to string

How to a byte array to a string? The solution is using the 'GetString()' method from the ASCIIEncoding.ASCII object. Be carrefull with this method, it may cause problems if you try to convert something other than English, such as Chinese and other asian languages. In this case, you have to use specific ASCII encoding for that language.
For example, you probably want to use System.Text.Encoding.GetEncoding(1251).GetString(b);
Here, '1251' stands for English. You can choose your own codepage for Encoding or Decoding.

byte[] data = ... ; //whatever it is here
string text1 = System.Text.ASCIIEncoding.ASCII.GetString(data);//Let the ASCIIEncoding handle the convertion
string text2 = System.Text.Encoding.GetEncoding(1251).GetString(data);// 1251 stands for English
string text3 = System.Text.Encoding.GetEncoding(28591).GetString(data);// 28591 stands for Latin
string text4 = System.Text.Encoding.GetEncoding("GB18030").GetString(data);// "GB18030" stands for Simplified Chinese


0 Responses to "C# How to convert byte arry to string"

Post a Comment



Copyright 2009 All Rights Reserved Revolution Two Lifestyle theme by Brian Gardner | Blogger template converted & enhanced by eBlog Templates