编码01

    class Program
    {
        static string text = "我爱你iloveyou";
        static void Main(string[] args)
        {
            byte[] b1 = Encoding.UTF8.GetBytes(text);
            Console.WriteLine(b1.Length);
            byte[] b2 = Encoding.Unicode.GetBytes(text);
            Console.WriteLine(b2.Length);
            string str = Encoding.UTF8.GetString(b1);
            Console.WriteLine(str);
            str = Encoding.Unicode.GetString(b2);
            Console.WriteLine(str);
            Console.Read();
        }
    }
}

分析:

C#中的char类型采用Unicode编码,每个字符占2个字节。string中的每个字符同样采用Unicode编码。

static string text = "我爱你iloveyou";

在静态区,存储text,采用Unicode编码,占用2*11个字节。

byte[] b1 = Encoding.UTF8.GetBytes(text);

(1)从静态区拿出text这2*11个字节

(2)每2个字节翻译成一个字符,再把该字符采用UTF8翻译成1或2或3或4或5或6个字节

(3)步骤(2)执行11次,得到一个新的字节数组,字节长度是3*3 + 8*1

byte[] b2 = Encoding.Unicode.GetBytes(text);

同上

string str = Encoding.UTF8.GetString(b1);

(1)拿出容量是17的字节数组

(2)采用UTF8翻译出一个字符串str1,字符个数仍旧是11

(3)再把str1采用Unicode翻译成一个22个字节的字节数组,赋值给string类型

str = Encoding.Unicode.GetString(b2);

同上

猜你喜欢

转载自www.cnblogs.com/riversouth/p/10296321.html
今日推荐