您的位置:首页 > 编程语言 > C#

C# string 和byte[]之间的转换

2015-12-14 09:53 579 查看

c#将string和byte数组之间互相转换

如下方法将字符串转换为byte数组,使用System.Buffer.BlockCopy方法。

static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}

将字节数组转换为字符串,同样是使用BlockCopy方法,这次是将字节数组复制到char数组中

static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}

//string 转为byte数组
byte[] array = Encoding.UTF8.GetBytes(content);

//将byte数组转为string
string result = Encoding.UTF8.GetString(array);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: