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);
相关文章推荐
- c# string Rmove Substring Replace
- c#进制学习
- base(C# 参考)
- C# 我理解的接口、抽象类、以及事件
- C# 模拟PrintScreen 和 Alt+PrintScreen
- 快速上手之 C#progressBar的实现
- C# Window Service详解
- abstract(C# 参考)
- C# 最原始的tree 递归使用
- C#——类和继承
- C#学习笔记——LINQ数据访问
- C# 静态类
- 【C#学习】——面向对象
- 【C#】——out和ref区别
- C#总结(三)
- 【C#】哈希表
- #递归 解决ABCDE 5人分鱼问题鱼,
- C#之显示
- (copy)C#时间日期操作
- C#输入限制(仅允许输入数字)