C#中Byte[]和String之间转换的方法_C#教程-查字典教程网
C#中Byte[]和String之间转换的方法
C#中Byte[]和String之间转换的方法
发布时间:2016-12-28 来源:查字典编辑
摘要:本文给大家介绍如何在Byte[]和String之间进行转换?比特(b):比特只有01,1代表有脉冲,0代表无脉冲。它是计算机物理内存保存的最...

本文给大家介绍如何在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("nn这是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("nnutf8: {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#教程学习
    热门C#教程学习
    编程开发子分类