Monday, March 17, 2008

How to convert a byte array to string and back

To convert byte array to string it is suggested to use class Encoding

class ConvertUtils:

public class ConvertUtils
{
public static string ConvertBytesToString(byte[] data)
{
return Encoding.GetEncoding(1251).GetString(data);
}
public static byte[] ConvertStringToBytes(string data)
{
return Encoding.GetEncoding(1251).GetBytes(data);
}
}

Example:

It is a very important to test converting with help of 0xFD..0xFF (253 - 255) values, because a some code pages cannot convert these values correct.

byte[] inputData = new byte[] {0, 1, 2, 3, 0xFD, 0xFE, 0xFF};
string convertedData = ConvertUtils.ConvertBytesToString(inputData);
byte[] outputData = ConvertUtils.ConvertStringToBytes(convertedData);

Results:

watchWindow

Reference

Encoding Class

No comments: