代码改变世界

C#中,类似native2ascii的方法

2007-03-19 14:06  清炒白菜  阅读(440)  评论(0编辑  收藏  举报
public static String native2ascii(String str)
        {
            
int code;
            
char[] chars = str.ToCharArray();
            StringBuilder sb 
= new StringBuilder(255);
            
for (int i = 0; i < chars.Length; i++)
            {
                
char c =chars[i];
                
if (c > 255)
                {
                    sb.Append(
"\\u");
                    code 
= (c >> 8);
                    
string tmp = code.ToString("X");
                    
if (tmp.Length == 1) sb.Append("0");
                    sb.Append(tmp);
                    code 
= (c & 0xFF);
                    tmp 
= code.ToString("X");
                    
if (tmp.Length == 1) sb.Append("0");
                    sb.Append(tmp);
                }
                
else
                {
                    sb.Append(c);
                }
 
            } 
return (sb.ToString());
        }