好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

原文链接:http://www.cnblogs.com/jushuai/archive/2016/08/02/5728524.html

dy("nrwz");

查看更多关于C#中Byte[]和String之间转换的方法的详细内容...

  阅读:45次