字符串与Unicode编码的相互转换

将字符串转换为Unicode编码形式的字符串

private static string ToUnicode(string chineseText)
        {
            if (chineseText.IsNullOrEmpty())
            {
                return string.Empty;
            }
            byte[] btChinese = Encoding.Unicode.GetBytes(chineseText);            
            StringBuilder sbunicode = new StringBuilder();
            for (int i = 0; i < btChinese.Length; i += 2)
            {
                sbunicode.Append(string.Concat("\\u" + btChinese[i + 1].ToString("x").PadLeft(2, '0'), btChinese[i].ToString("x").PadLeft(2, '0')));
            }
            return sbunicode.ToString();
        }

将Unicode形式的字符串转换为正常的字符串

private static string ToGB2312(string unicodeText)
        {
            if (unicodeText.IsNullOrEmpty())
            {
                return string.Empty;
            }
            MatchCollection mcUnicodes= Regex.Matches(unicodeText, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (mcUnicodes.Count < 1)
            {
                return string.Empty;
            }
            byte[] bts = new byte[2];
            StringBuilder sbChinese = new StringBuilder(mcUnicodes.Count);           
            foreach (Match mUnicode in mcUnicodes)
            {
                bts[0] = (byte)int.Parse(mUnicode.Groups[2].Value, NumberStyles.HexNumber);
                bts[1] = (byte)int.Parse(mUnicode.Groups[1].Value, NumberStyles.HexNumber);
                sbChinese.Append( Encoding.Unicode.GetString(bts));
            }
            return sbChinese.ToString();
        }

 

posted @ 2013-03-22 10:38  DCLancer  阅读(572)  评论(0编辑  收藏  举报
(function() { var c = document.createElement('script'); c.type = 'text/javascript'; c.async = true; c.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.clicki.cn/boot/48212'; var h = document.getElementsByTagName('script')[0]; h.parentNode.insertBefore(c, h); })();