c#编程指南(十七) 字符串和字节流相互转化

字符串和字节流的转化,主要用的是System.Text.Encoding类,下面的代码示例,实现了UTF8,UTF32,GB2312常用编码的文本转化,代码很简单,

也不用解释,放在这里供大家参考,方便之余,还是赞叹一个.net的给力吧!!

  
    
1 using System;
2   using System.Collections.Generic;
3 using System.Text;
4
5 namespace TextEncoder
6 {
7 class Program
8 {
9 private static string _test = " Abc " ;
10 //
11 static void Main( string [] args)
12 {
13 // ASCII,UTF7,UTF8,UTF32,UNICODE
14 byte [] bytes1 = Encoding.ASCII.GetBytes(_test);
15 byte [] bytes2 = Encoding.UTF8.GetBytes(_test);
16 byte [] bytes3 = Encoding.Unicode.GetBytes(_test);
17 //
18 string s1 = Encoding.ASCII.GetString(bytes1);
19 string s2 = Encoding.UTF8.GetString(bytes2);
20 string s3 = Encoding.Unicode.GetString(bytes3);
21 //
22 // GB2312,BIG5
23 byte [] bytes4 = Encoding.GetEncoding( " GB2312 " ).GetBytes(_test);
24 byte [] bytes5 = Encoding.GetEncoding( " BIG5 " ).GetBytes(_test);
25 //
26 string s4 = Encoding.GetEncoding( " GB2312 " ).GetString(bytes4);
27 string s5 = Encoding.GetEncoding( " BIG5 " ).GetString(bytes5);
28 //
29 Console.WriteLine(s1 + " ; " + s2 + " ; " + s3 + " ; " + s4 + " ; " + s5);
30 }
31 }
32 }

 

你可能感兴趣的:(字符串)