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

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);
原文地址:https://www.cnblogs.com/ting5/p/5044252.html