2014/07/29

How to convert byte array to string and string to byte array in C# ?

public static byte[] GetByteArrayFromString(string s)
{
byte[] bytes = new byte[s.Length * sizeof(char)];
System.Buffer.BlockCopy(s.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static string GetStringFromByteArray(byte[] bytesArr)
{
char[] chars = new char[bytesArr.Length / sizeof(char)];
System.Buffer.BlockCopy(bytesArr, 0, chars, 0, bytesArr.Length);
return new string(chars);
}
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment