我必须转换以下十六进制编码的字符串:
56 6f 6e 68 c3 b6 67 65 6e
结果应该是:Vonhöger
但是,我得到的结果是:Vonhöger
我的代码出了什么问题?
For x = 0 To hexString.Length - 1 Step 2
Dim k As String = hexString.Substring(x, 2)
If (k <> "X'") Then
com &= Chr(Val("&h" & k))
End If
Next
答案 0 :(得分:3)
您正在将每个字节转换为unicode字符,但数据是UTF-8编码的,因此组合的某些字节形成一个字符。字节c3 b6
是ö
character的代码。
将数据转换为字节,然后将其解码为UTF-8:
Dim hexString = "566f6e68c3b667656e"
Dim bytes() As Byte
ReDim bytes(hexString.Length \ 2 - 1)
For i As Integer = 0 To bytes.Length - 1
bytes(i) = Convert.ToByte(hexString.Substring(i * 2, 2), 16)
Next
Dim com As String = Encoding.UTF8.GetString(bytes)
答案 1 :(得分:0)
与其他建议类似:
<Extension>
Public Function FromHexToUnicodeString(target As String) As String
Dim bytes((target.Length \ 2) - 1) As Byte
For b = 0 To bytes.Length - 1
bytes(b) = Convert.ToByte(target.Substring(b * 2, 2), 16)
Next
Return Text.Encoding.UTF8.GetString(bytes)
End Function
用法:
MessageBox.Show("566f6e68c3b667656e".FromHexToUnicodeString)