2011-08-29 89 views
1

我有「74657374696e67」(即「測試」)字符串,十六進制編碼的unicode文本。需要將其轉換回可讀輸出。 如何在.NET中做到這一點?將十六進制編碼的字符串轉換爲unicode文本

更新:

文本使用下面的Visual Basic 6函數最初編碼:

Public Function EnHex(Data As String) As String 
    Dim iCount As Double, sTemp As String 
    Reset 
    For iCount = 1 To Len(Data) 
     sTemp = Hex$(Asc(Mid$(Data, iCount, 1))) 
     If Len(sTemp) < 2 Then sTemp = "0" & sTemp 
     Append sTemp 
    Next 
    EnHex = GData 
    Reset 
End Function 

解碼如下進行:

Public Function DeHex(Data As String) As String 
    Dim iCount As Double 
    Reset 
    For iCount = 1 To Len(Data) Step 2 
     Append Chr$(Val("&H" & Mid$(Data, iCount, 2))) 
    Next 
    DeHex = GData 
    Reset 
End Function 
+0

十六進制數字表示字節,但Unicode文本是如何編碼爲字節的第一位?有不止一個選擇。 –

+0

您引用的編碼函數會超過255以外的Unicode代碼點,因此您可以假設您的十六進制字符串描述Latin-1文本而不是Unicode。 –

回答

0

有趣的問題。

google搜索了一下,我發現這個在VB.NET

Function FromHex(ByVal Text As String) As String 

    If Text Is Nothing OrElse Text.Length = 0 Then 
    Return String.Empty 
    End If 

    Dim Bytes As New List(Of Byte) 
    For Index As Integer = 0 To Text.Length - 1 Step 2 
    Bytes.Add(Convert.ToByte(Text.Substring(Index, 2), 16)) 
    Next 

    Dim E As System.Text.Encoding = System.Text.Encoding.Unicode 
    Return E.GetString(Bytes.ToArray) 

End Function 
+0

此代碼由於某種原因無法工作。 ArgumentOutOfRangeException,「索引和長度必須引用字符串中的位置。」 – SharpAffair

0
var myString = System.Text.Encoding.UTF8.GetString(DecodeHexString("74657374696e67")); 

public static byte[] DecodeHexString(string str) 
{ 
    uint num = (uint) (str.Length/2); 
    byte[] buffer = new byte[num]; 
    int num2 = 0; 
    for (int i = 0; i < num; i++) 
    { 
     buffer[i] = (byte) ((HexToByte(str[num2]) << 4) | HexToByte(str[num2 + 1])); 
     num2 += 2; 
    } 
    return buffer; 
} 

private static byte HexToByte(char val) 
{ 
    if ((val <= '9') && (val >= '0')) 
    { 
     return (byte) (val - '0'); 
    } 
    if ((val >= 'a') && (val <= 'f')) 
    { 
     return (byte) ((val - 'a') + 10); 
    } 
    if ((val >= 'A') && (val <= 'F')) 
    { 
     return (byte) ((val - 'A') + 10); 
    } 
    return 0xff; 
} 
0

在我看來,該EnHex和DeHex被假定在原始字符串中的字符的ASCII編碼,或在一些編碼其他字符集,其中所有字符在0-255範圍內。因此所有的字符都可以用一個兩個字符的十六進制數來表示以下.NET(C#)代碼將解碼十六進制編碼的字符串:

public string DecodeHex(string input) 
    { 
     if (input.Length % 2 == 1) 
      throw new ArgumentException("Invalid hex encoded string."); 

     int len = input.Length/2; 
     StringBuilder output = new StringBuilder(len); 
     for (int c = 0; c < len; ++c) 
      output.Append((char)System.Convert.ToByte(input.Substring(c*2, 2), 16)); 

     return output.ToString(); 
    } 

這正是這個online hex decoder在做什麼。用它來測試你的結果和期望。

相關問題