承接上篇 C# 與 VB6 Encode,本文提供 VB6 Decode 函數完整代碼,將 4 字元十六進位字串 (Unicode code point) 還原為字串,包含錯誤處理與異常字元檢測。
'*******************************************************************
' 函數:Decode
' 作用:將 16 進位資料編碼轉換為字串,為 Encode 逆過程
' 參數:strDecode - 4 字元一組的十六進位字串 (如 "00330041")
' 回傳:解碼後字串,失敗時回傳原字串並記錄錯誤
'*******************************************************************
Public Function Decode(strDecode As String) As String
Dim i As Long
Dim strCode As String ' 4 字元暫存
Dim chrTmp As String ' 解碼後單一字元
On Error GoTo ErrProc
' 長度必須為 4 的倍數
If Len(strDecode) Mod 4 <> 0 Then GoTo ErrProc
For i = 1 To Len(strDecode) Step 4
strCode = Mid$(strDecode, i, 4) ' 取 4 字元
chrTmp = ChrW("&H" & strCode) ' 十六進位轉 Unicode 字元
' 特殊檢查:ChrW 回傳 "?" 可能為真正的 U+003F 或無效編碼
If chrTmp = "?" Then
If strCode <> "003F" Then GoTo ErrProc ' 非真正問號視為錯誤
End If
Decode = Decode & chrTmp
Next
Exit Function
ErrProc:
Decode = strDecode
DealwithEvents "不能解析的訊息:" & strDecode
End Function
'*******************************************************************
| 步驟 | 代碼 | 說明 |
|---|---|---|
| 長度驗證 | Len(strDecode) Mod 4 <> 0 | 每字元固定 4 位十六進位 (U+0000~U+FFFF) |
| 逐組解碼 | Mid$(strDecode, i, 4) | VB6 字串 1-based 索引 |
| 十六進位轉字元 | ChrW("&H" & strCode) | &H 前綴標示十六進位常值,ChrW 回傳 Unicode 字元 |
| 問號歧義處理 | If chrTmp = "?" Then If strCode <> "003F" Then Err | U+003F 為真正問號,其他無法顯示字元也會回傳 "?",需排除 |
| 錯誤處理 | On Error GoTo ErrProc | 統一跳轉錯誤標籤,回傳原字串並記錄日誌 |