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

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C#byte[]转string,string转byte[]的四种⽅法
转载:https:///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库才能使⽤。

相关文档
最新文档