2011-01-11 2 views
3

인코딩 된 유니 코드 문자 "& #xfc;"이 포함 된 문자열로 시작됩니다. 문자열을 일부 논리를 수행하고 다른 문자열을 반환하는 객체에 전달합니다. 이 문자열은 원래 인코딩 된 문자를 유니 코드로 "ü"으로 변환합니다.유니 코드 문자를 이스케이프 처리 된 ASCII로 변환하는 방법 #

원본 인코딩 된 문자를 다시 가져올 필요가 있지만 지금까지 불가능합니다. I는 HttpUtility.HtmlEncode() 메소드를 사용하여 시도 갖지만 반환

"& # 252;"동일하지 않다.

아무도 도와 줄 수 있습니까?

+0

어떤 점에서 그렇지 않은 같은? –

답변

4

디스플레이 용도로는 거의 동일합니다. HttpUtility.HtmlEncode은 십진수 인코딩을 사용하고 있습니다. 원래 인코딩은 &#DECIMAL;이고 원래 버전은 hexadecimal인데, 형식은 &#xHEX;입니다. 16 진수의 fc은 십진수로 252이므로이 둘은 동일합니다.

16 진수로 인코딩 된 버전을 얻으려면 converting it to hex을 구문 분석 한 다음 &#xHEX; 형식으로 다시 채워 넣는 것이 좋습니다. 예 :

string unicode = "ü"; 
string decimalEncoded = HttpUtility.HtmlEncode(unicode); 
int decimal = int.Parse(decimalEncoded.Substring(2, decimalEncoded.Length - 3); 
string hexEncoded = string.Format("&#x{0:X};", decimal); 
0

나는 어제이 일을 정리해야했습니다.

단일 문자를 보는 것보다 조금 복잡합니다. 자신의 HtmlEncode() 메서드를 롤업해야합니다. .Net 세계의 문자열은 UTF-16으로 인코딩됩니다. 유니 코드 코드 포인트 (HTML 숫자 문자 참조가 식별하는 것)는 32 비트 부호없는 정수 값입니다. 이것은 주로 유니 코드 "기본 다국 언어"이외의 문자를 처리해야한다는 점에서 문제입니다.

이 코드는이 도움이

using System; 
using System.Configuration ; 
using System.Globalization ; 
using System.Collections.Generic ; 
using System.Text; 


namespace TestDrive 
{ 
    class Program 
    { 
     static void Main() 
     { 
      string src = "foo \uABC123 bar" ; 
      string converted = HtmlEncode(src) ; 

      return ; 
     } 

     static string HtmlEncode(string s) 
     { 
      // 
      // In the .Net world, strings are UTF-16 encoded. That means that Unicode codepoints greater than 0x007F 
      // are encoded in the string as 2-character digraphs. So to properly turn them into HTML numeric 
      // characeter references (decimal or hex), we first need to get the UTF-32 encoding. 
      // 
      uint[]  utf32Chars = StringToArrayOfUtf32Chars(s) ; 
      StringBuilder sb   = new StringBuilder(2000) ; // set a reasonable initial size for the buffer 

      // iterate over the utf-32 encoded characters 
      foreach (uint codePoint in utf32Chars) 
      { 

       if (codePoint > 0x0000007F) 
       { 
        // if the code point is greater than 0x7F, it gets turned into an HTML numerica character reference 
        sb.AppendFormat("&#x{0:X};" , codePoint) ; // hex escape sequence 
        //sb.AppendFormat("&#{0};" , codePoint) ; // decimal escape sequence 
       } 
       else 
       { 
        // if less than or equal to 0x7F, it goes into the string as-is, 
        // except for the 5 SGML/XML/HTML reserved characters. You might 
        // want to also escape all the ASCII control characters (those chars 
        // in the range 0x00 - 0x1F). 

        // convert the unit to an UTF-16 character 
        char ch = Convert.ToChar(codePoint) ; 

        // do the needful. 
        switch (ch) 
        { 
        case '"' : sb.Append("""  ) ; break ; 
        case '\'' : sb.Append("'"  ) ; break ; 
        case '&' : sb.Append("&"  ) ; break ; 
        case '<' : sb.Append("&lt;"  ) ; break ; 
        case '>' : sb.Append("&gt;"  ) ; break ; 
        default : sb.Append(ch.ToString()) ; break ; 
        } 
       } 
      } 

      // return the escaped, utf-16 string back to the caller. 
      string encoded = sb.ToString() ; 
      return encoded ; 
     } 

     /// <summary> 
     /// Convert a UTF-16 encoded .Net string into an array of UTF-32 encoding Unicode chars 
     /// </summary> 
     /// <param name="s"></param> 
     /// <returns></returns> 
     private static uint[] StringToArrayOfUtf32Chars(string s) 
     { 
      Byte[] bytes  = Encoding.UTF32.GetBytes(s) ; 
      uint[] utf32Chars = (uint[]) Array.CreateInstance(typeof(uint) , bytes.Length/sizeof(uint)) ; 

      for (int i = 0 , j = 0 ; i < bytes.Length ; i += 4 , ++j) 
      { 
       utf32Chars[ j ] = BitConverter.ToUInt32(bytes , i) ; 
      } 

      return utf32Chars ; 
     } 




    } 

} 

희망하고 싶은 일을해야한다!

0

또는 당신은이 코드를 시도 할 수 있습니다 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Web; 
using System.Configuration; 
using System.Globalization; 

namespace SimpleCGIEXE 
{ 
    class Program 
    { 
     static string Uni2Html(string src) 
     { 
      string temp1 = HttpUtility.UrlEncodeUnicode(src); 
      string temp2 = temp1.Replace('+', ' '); 
      string res = string.Empty; 
      int pos1 = 0, pos2 = 0; 
      while (true){ 
       pos2=temp2.IndexOf("%",pos1); 
       if (pos2 < 0) break; 
       if (temp2[pos2 + 1] == 'u') 
       { 
        res += temp2.Substring(pos1, pos2 - pos1); 
        res += "&#x"; 
        res += temp2.Substring(pos2 + 2, 4); 
        res += ";"; 
        pos1 = pos2 + 6; 
       } 
       else 
       { 
        res += temp2.Substring(pos1, pos2 - pos1); 
        string stASCII = temp2.Substring(pos2 + 1, 2); 
        byte[] pdASCII = new byte[1]; 
        pdASCII[0] = byte.Parse(stASCII, System.Globalization.NumberStyles.AllowHexSpecifier); 
        res += Encoding.ASCII.GetString(pdASCII); 
        pos1 = pos2 + 3; 
       } 
      } 
      res += temp2.Substring(pos1); 
      return res; 
     } 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Content-type: text/html;charset=utf-8\r\n"); 
      String st = "Vietnamese string: Thử một xâu unicode @@ # ~ .^ % !"; 
      Console.WriteLine(Uni2Html(st) + "<br>"); 
      st = "A chinese string: 我爱你 (I love you)"; 
      Console.WriteLine(Uni2Html(st) + "<br>"); 
     } 
    } 
} 
+0

당신은 당신의 대답에 대해 SO에게 약간의 설명을 할 수 있습니다. 감사. –