其他分享
首页 > 其他分享> > utf8拥有的字符Ş ,但是gb2312没有Ş ,而gb18030有Ş

utf8拥有的字符Ş ,但是gb2312没有Ş ,而gb18030有Ş

作者:互联网

https://en.wikipedia.org/wiki/List_of_Unicode_characters

选取一个特殊字符

U+015E Ş 350 Ş Latin Capital Letter S with cedilla 0286 

然后尝试处理

 

 [Test]
        public void Test20210521002()
        {
            var str = "Ş";
            //PrintHexString(Encoding.ASCII, str);  //ascii本身不支持中文的,所以打印出来的是错误的
            PrintHexString(Encoding.UTF8, str);
            PrintHexString(Encoding.BigEndianUnicode, str);
            PrintHexString(Encoding.GetEncoding(936), str);
            PrintHexString(Encoding.GetEncoding(54936), str);
        }

        private void PrintHexString(Encoding encoding, string str)
        {
            int count = 0;
            foreach (var c in str)
            {
                var array = encoding.GetBytes(c.ToString());
                var hexString = GetHexString(array);
                Console.WriteLine($"{c}, {encoding.WebName}, U+{hexString}, {string.Join(string.Empty,array.Select(GetBinaryString))}");
                count += array.Length;
            }
            Console.WriteLine($"【{str}】 occupy {count} bytes when encoded by {encoding.WebName}");
            Console.WriteLine();
        }

        private string GetBinaryString(byte b)
        {
            return Convert.ToString(b, 2).PadLeft(8, '0');
        }

        private string GetHexString(byte[] array)
        {
            var list = array.Select(x => x.ToString("X2"));
            var str = string.Join(string.Empty, list);
            return str;
        }

        [Test]
        public void Test20210521003()
        {
            var array = new byte[] {0xc5, 0x9e};
            Encoding utf8 = Encoding.UTF8;
            var str1 = utf8.GetString(array);
            Console.WriteLine(str1);

            var array4 = new byte[] { 0x01, 0x5e };
            Encoding utf16 = Encoding.BigEndianUnicode;
            var str4 = utf16.GetString(array4);
            Console.WriteLine(str4);

            var array2 = new byte[] {0x35};
            Encoding gb2312 = Encoding.GetEncoding(936);
            var str2 = gb2312.GetString(array2);
            Console.WriteLine(str2);

            var array3 = new byte[] {0x81, 0x30, 0x94, 0x35};
            Encoding gb18030 = Encoding.GetEncoding(54936);
            var str3 = gb18030.GetString(array3);
            Console.WriteLine(str3);

        }

Ş, utf-8, U+C59E, 1100010110011110
【Ş】 occupy 2 bytes when encoded by utf-8

Ş, utf-16BE, U+015E, 0000000101011110
【Ş】 occupy 2 bytes when encoded by utf-16BE

Ş, gb2312, U+3F, 00111111  这个是错误的
【Ş】 occupy 1 bytes when encoded by gb2312

Ş, GB18030, U+81309435, 10000001001100001001010000110101
【Ş】 occupy 4 bytes when encoded by GB18030

 

把上面的字节,反过来输出成字符的话

Ş  utf8
Ş   utf16
5   gb2312  因为上面的输出就是错误的,所以这里没法得到正确的。而且gb2312本身不支持Ş 
Ş  gb18030

 

标签:gb18030,Console,string,Encoding,utf8,gb2312,str,var,array
来源: https://www.cnblogs.com/chucklu/p/14793394.html