C#中Byte[]和String之间转换的方法

很多朋友不清楚如何在Byte[]和String之间进行转换?下面小编给大家带来了byte与string转换的方法,感兴趣的朋友参考下吧

本文给大家介绍如何在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之间转换的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对html中文网网站的支持!

以上就是C#中Byte[]和String之间转换的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程