欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > C# >内容正文

C#

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

发布时间:2025/3/15 C# 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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

总结

以上是生活随笔为你收集整理的C# string 和byte[]之间的转换的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。