C# byte[]转string, string转byte[] 的四种方法

转载:https://blog.csdn.net/tom_221x/article/details/71643015

第一种

  1. string str = System.Text.Encoding.UTF8.GetString(bytes);
  2. byte[] decBytes = System.Text.Encoding.UTF8.GetBytes(str);

同样的,System.Text.Encoding.Default,System.Text.Encoding.ASCII也是可以的。还可以使用System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0')给字符串加上结束标识。

第二种

  1. string str = BitConverter.ToString(bytes);
  2. String[] tempArr = str.Split('-');
  3. byte[] decBytes = new byte[tempArr.Length];
  4. for (int i = 0; i < tempArr.Length; i++)
  5. {
  6. decBytes[i] = Convert.ToByte(tempArr[i], 16);
  7. }

这种方法会给字符串加上 '-' 连字符,并且没有函数转换回去。所以需要手动转换为bytes。

第三种

  1. string str = Convert.ToBase64String(bytes);
  2. byte[] decBytes = Convert.FromBase64String(str);

这种方法简单明了,完美无问题。需要注意的是,转换出来的string可能会包含 '+','/' , '=' 所以如果作为url地址的话,需要进行encode。

第四种

  1. string str = HttpServerUtility.UrlTokenEncode(bytes);
  2. byte[] decBytes = HttpServerUtility.UrlTokenDecode(str);

这种方法会自动编码url地址的特殊字符,可以直接当做url地址使用。但需要依赖System.Web库才能使用。