2012-04-27 90 views
2

可能重複:
.NET Convert from string of Hex values into Unicode characters (Support different code pages)轉換的ASCII字符串轉換成正常的字符串C#

展望包含ASCII字符串轉換成文本字符串轉換,我似乎只能找到從Byte []轉換的System.Text.ASCIIEncoding.ASCII.GetString,但在這種情況下,我希望能夠從字符串中完成。

its a string containing ASCII hex: For example : ASCI = 47726168616D would equal Graham

是否有任何內置的功能呢?幫助將不勝感激,謝謝。

+2

您的代碼請 – 2012-04-27 11:27:01

+3

什麼是C#中的正常字符串? – mloskot 2012-04-27 11:27:21

+4

@Graham嘗試將字符串轉換爲byte [],然後應用System.Text.ASCIIEncoding.ASCII.GetString – Milee 2012-04-27 11:27:45

回答

6
private static string GetStringFromAsciiHex(String input) 
{ 
    if (input.Length % 2 != 0) 
     throw new ArgumentException("input"); 

    byte[] bytes = new byte[input.Length/2]; 

    for (int i = 0; i < input.Length; i += 2) 
    { 
     // Split the string into two-bytes strings which represent a hexadecimal value, and convert each value to a byte 
     String hex = input.Substring(i, 2); 
     bytes[i/2] = Convert.ToByte(hex, 16);     
    } 

    return System.Text.ASCIIEncoding.ASCII.GetString(bytes); 
}