如何在Byte[]和String之间进行转换

源自C#与.NET程序员面试宝典。


如何在Byte[]和String之间进行转换?
比特(b):比特只有0 1,1代表有脉冲,0代表无脉冲。它是计算机物理内存保存的最基本单元。
字节(B):8个比特,0—255的整数表示
编码:字符必须编码后才能被计算机处理。早期计算机使用7为AscII编码,为了处理汉字设计了中文简体GB2312和big5

字符串与字节数组之间的转换,事实上是现实世界的信息和数字世界信息之间的转换,势必涉及到某种编码方式,不同的编码方式将导致不同的转换结果。C#中常使用System.Text.Encoding来管理常用的编码。下面直接上代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ByteToString
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string str = "鞠哥真帅!";
14 
15             //使用UTF编码。。。
16             Byte[] utf8 = StrToByte(str, Encoding.UTF8);
17             //估计C#当时设计时没有中文简体,这是后来中国搞的?
18             Byte[] gb2312 = StrToByte(str,Encoding.GetEncoding("GB2312"));
19 
20             Console.WriteLine("这是UTF8(鞠哥真帅),长度是:{0}",utf8.Length);
21             foreach (var item in utf8)
22             {
23                 Console.Write(item);
24             }
25 
26             Console.WriteLine("\n\n这是gb2312(鞠哥真帅),长度是:{0}",gb2312.Length);
27             foreach (var item in gb2312)
28             {
29                 Console.Write(item);
30             }
31 
32 
33             //用utf8编码的字节数组转换为str
34             string utf8Str = ByteToStr(utf8,Encoding.UTF8);
35             string gb2312Str = ByteToStr(gb2312,Encoding.GetEncoding("GB2312"));
36 
37             Console.WriteLine("\n\nutf8: {0}",utf8Str);
38             Console.WriteLine("gb2312: {0}",gb2312Str);
39             Console.ReadKey();
40 
41         }
42 
43 
44         //C#通常使用System.Text.Encoding编码
45 
46         //字符串转数组
47         static Byte[] StrToByte(string str, Encoding encoding)
48         {
49            return encoding.GetBytes(str);
50         }
51 
52         //数组转换字符串
53         static String ByteToStr(Byte[] bt,Encoding encoding)
54         {
55             return encoding.GetString(bt);
56         }
57 
58     }
59 }

 

posted @ 2016-08-02 11:11  鞠帅  阅读(11282)  评论(2编辑  收藏  举报