C#字串与Unicode互相转换方法

/// <summary>
        /// 将原始字串转换为unicode,格式为\u....\u....
        /// </summary>
        /// <param name="srcText"></param>
        /// <returns></returns>
        private string StringToUnicode(string srcText)
        {
            string dst = "";
            char[] src = srcText.ToCharArray();
            for (int i = 0; i < src.Length; i++)
            {
                byte[] bytes = Encoding.Unicode.GetBytes(src[i].ToString());
                string str = @"\u" + bytes[1].ToString("X2") + bytes[0].ToString("X2");
                dst += str;
            }
            return dst;
        }

        /// <summary>
        /// 将Unicode字串\u....\u....格式字串转换为原始字符串
        /// </summary>
        /// <param name="srcText"></param>
        /// <returns></returns>
        private string UnicodeToString(string srcText)
        {
            string dst = "";
            string src = srcText;
            int len = srcText.Length / 6;
            
            for (int i = 0; i <= len - 1; i++)
            {
                string str = "";
                str = src.Substring(0, 6).Substring(2);
                src = src.Substring(6);
                byte[] bytes = new byte[2];
                bytes[1] = byte.Parse(int.Parse(str.Substring(0, 2), NumberStyles.HexNumber).ToString());
                bytes[0] = byte.Parse(int.Parse(str.Substring(2, 2), NumberStyles.HexNumber).ToString());
                dst += Encoding.Unicode.GetString(bytes);
            }
            return dst;
        }

 

string aa = QConnectSDK.CustomWebRequest.getResponse("http://192.168.28.64:1000/", QConnectSDK.Method.GET, null).Replace("charset=gb2312", "charset=utf-8");
        //string utfStr = GB2312ToUtf8(aa);
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("~/2.htm"), false, Encoding.UTF8))
        {
            sw.Write(aa);
        }
    }
    public string GB2312ToUtf8(string gb2312String)
    {
        Encoding fromEncoding = Encoding.GetEncoding("gb2312");
        Encoding toEncoding = Encoding.UTF8;
        return EncodingConvert(gb2312String, fromEncoding, toEncoding);
    }

    public string Utf8ToGB2312(string utf8String)
    {
        Encoding fromEncoding = Encoding.UTF8;
        Encoding toEncoding = Encoding.GetEncoding("gb2312");
        return EncodingConvert(utf8String, fromEncoding, toEncoding);
    }

    public string EncodingConvert(string fromString, Encoding fromEncoding, Encoding toEncoding)
    {
        byte[] fromBytes = fromEncoding.GetBytes(fromString);
        byte[] toBytes = Encoding.Convert(fromEncoding, toEncoding, fromBytes);

        string toString = toEncoding.GetString(toBytes);
        return toString;
    }

 

posted @ 2012-11-13 17:22  一千零一夜  阅读(1149)  评论(0编辑  收藏  举报