首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

字串與十六進位雙向轉換 (下):VB6 Decode 函數完整實現

     編輯:關於C語言

前言

承接上篇 C# 與 VB6 Encode,本文提供 VB6 Decode 函數完整代碼,將 4 字元十六進位字串 (Unicode code point) 還原為字串,包含錯誤處理與異常字元檢測。

VB6 Decode 函數代碼

'*******************************************************************
' 函數: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
'*******************************************************************

關鍵邏輯解析

C# 對應實現 (參考)

public static string Decode(string strDecode)
{
    if (strDecode.Length % 4 != 0) return strDecode;
    var sb = new StringBuilder();
    for (int i = 0; i < strDecode.Length; i += 4)
    {
        string hex = strDecode.Substring(i, 4);
        if (ushort.TryParse(hex, NumberStyles.HexNumber, null, out ushort codePoint))
            sb.Append((char)codePoint);
        else
            return strDecode; // 解析失敗
    }
    return sb.ToString();
}

編碼格式定義 (Encode/Decode 共用)

  • 單字元編碼:Unicode code point → 4 位大寫十六進位 (零填補)
  • 範例:'3' (U+0033) → "0033";'我' (U+6211) → "6211"
  • 字串編碼:逐字元拼接,"3我" → "00336211"
  • 適用範圍:BMP 字元 (U+0000~U+FFFF),補充平面字元需擴充為 8 位或 UTF-16 代理對

總結

VB6 Decode 以 ChrW("&Hxxxx") 實現十六進位轉 Unicode,關鍵在於 Mid$ 切分、&H 十六進位常值語法、以及問號歧義的特殊判斷。搭配上篇 Encode (雙位元組 AscB/MidB$ 組合),形成完整的字串↔十六進位雙向轉換工具,適用於舊系統資料遷移、通訊協定解析等場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
步驟代碼說明
長度驗證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 ErrU+003F 為真正問號,其他無法顯示字元也會回傳 "?",需排除
錯誤處理On Error GoTo ErrProc統一跳轉錯誤標籤,回傳原字串並記錄日誌