C#中Byte[]和String之间转换的方法
2016-08-02 14:10
906 查看
本文给大家介绍如何在Byte[]和String之间进行转换?
比特(b):比特只有0 1,1代表有脉冲,0代表无脉冲。它是计算机物理内存保存的最基本单元。
字节(B):8个比特,0―255的整数表示
编码:字符必须编码后才能被计算机处理。早期计算机使用7为AscII编码,为了处理汉字设计了中文简体GB2312和big5
字符串与字节数组之间的转换,事实上是现实世界的信息和数字世界信息之间的转换,势必涉及到某种编码方式,不同的编码方式将导致不同的转换结果。C#中常使用System.Text.Encoding来管理常用的编码。下面直接上代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ByteToString { class Program { static void Main(string[] args) { string str = "鞠哥真帅!"; //使用UTF编码。。。 Byte[] utf8 = StrToByte(str, Encoding.UTF8); //估计C#当时设计时没有中文简体,这是后来中国搞的? Byte[] gb2312 = StrToByte(str,Encoding.GetEncoding("GB2312")); Console.WriteLine("这是UTF8(鞠哥真帅),长度是:{0}",utf8.Length); foreach (var item in utf8) { Console.Write(item); } Console.WriteLine("\n\n这是gb2312(鞠哥真帅),长度是:{0}",gb2312.Length); foreach (var item in gb2312) { Console.Write(item); } //用utf8编码的字节数组转换为str string utf8Str = ByteToStr(utf8,Encoding.UTF8); string gb2312Str = ByteToStr(gb2312,Encoding.GetEncoding("GB2312")); Console.WriteLine("\n\nutf8: {0}",utf8Str); Console.WriteLine("gb2312: {0}",gb2312Str); Console.ReadKey(); } //C#通常使用System.Text.Encoding编码 //字符串转数组 static Byte[] StrToByte(string str, Encoding encoding) { return encoding.GetBytes(str); } //数组转换字符串 static String ByteToStr(Byte[] bt,Encoding encoding) { return encoding.GetString(bt); } } }
以上所述是小编给大家介绍的C#中Byte[]和String之间转换的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章:
相关文章推荐
- C# char和byte 以及string之间的转换问题
- C# Stream、string 和 byte[] 之间的转换
- c#中的char byte string 类型之间的转换
- C# string 和byte[]之间的转换
- string和byte[]之间的转换 (C#)
- C#中图片.BYTE[]和base64string的转换方法
- C#中string转换成字节byte的处理方法
- C#中String转换为sbyte*的方法
- C#中char[]与string之间的转换;byte[]与string之间的转化
- C# string和byte[]之间转换
- C# 图片与byte[]之间以及byte[]与string之间的转换
- [c#]string和byte 数组转换的快速方法(采用unsafe)
- C#中String转换为sbyte*的方法
- C# 图片与byte[]之间以及byte[]与string之间的转换
- C# 字符串string和内存流MemoryStream及比特数组byte[]之间相互转换
- c#byte[]和string,Image;Stream 和 文件之间的转换
- 详谈C# 图片与byte[]之间以及byte[]与string之间的转换
- c#中字节数组byte[]、图片image、流stream,字符串string、内存流MemoryStream、文件file,之间的转换
- C# 图片与byte[]之间以及byte[]与string之间的转换
- c#中字节数组byte[]、图片image、流stream,字符串string、内存流MemoryStream、文件file,之间的转换