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

字串與十六進位雙向轉換 (上):C# Encode/Decode 與 VB6 Encode 完整實現

     編輯:關於C語言

前言

字串與十六進位雙向轉換常用於通訊協定、日誌記錄、資料遷移。本文提供 C# 標準實現與 VB6 相容實現,編碼規則:每字元 → Unicode code point → 4 位大寫十六進位 (零填補)。

C# 標準實現

public static class HexStringConverter
{
    /// 
    /// 字串 → 十六進位 (每字元 4 位,Unicode code point)
    /// 
    public static string Encode(string strEncode)
    {
        var sb = new StringBuilder(strEncode.Length * 4);
        foreach (char c in strEncode)
            sb.Append(((ushort)c).ToString("X4")); // 強制 4 位大寫
        return sb.ToString();
    }

    /// 
    /// 十六進位 → 字串 (4 位一組)
    /// 
    public static string Decode(string strDecode)
    {
        if (strDecode.Length % 4 != 0) return strDecode; // 或拋出異常
        var sb = new StringBuilder(strDecode.Length / 4);
        for (int i = 0; i < strDecode.Length; i += 4)
        {
            string hex = strDecode.Substring(i, 4);
            if (ushort.TryParse(hex, NumberStyles.HexNumber, null, out ushort cp))
                sb.Append((char)cp);
            else
                return strDecode; // 解析失敗
        }
        return sb.ToString();
    }
}

測試案例

var original = "3我A";
var encoded = HexStringConverter.Encode(original); // "003362110041"
var decoded = HexStringConverter.Decode(encoded);  // "3我A"
Console.WriteLine($"原始:{original} 編碼:{encoded} 解碼:{decoded}");

VB6 Encode 實現 (相容舊系統)

'*******************************************************************
' 函數:Encode
' 作用:字串 → 16 進位編碼 (每字元 4 位,高位在前)
' 參數:strEncode - 原始字串
' 回傳:十六進位字串
'*******************************************************************
Public Function Encode(strEncode As String) As String
    Dim i As Long
    Dim chrTmp As String
    Dim ByteLower As String, ByteUpper As String
    Dim strReturn As String

    For i = 1 To Len(strEncode)
        chrTmp = Mid(strEncode, i, 1)           ' 取單字元

        ' VB6 字串為雙位元組 (DBCS/Unicode),取低位元組、高位元組
        ByteLower = Hex$(AscB(MidB$(chrTmp, 1, 1)))  ' 低位元組
        If Len(ByteLower) = 1 Then ByteLower = "0" & ByteLower
        ByteUpper = Hex$(AscB(MidB$(chrTmp, 2, 1)))  ' 高位元組
        If Len(ByteUpper) = 1 Then ByteUpper = "0" & ByteUpper

        strReturn = strReturn & ByteUpper & ByteLower ' 高位在前
    Next

    Encode = strReturn
End Function
'*******************************************************************

VB6 關鍵點解析

C# vs VB6 編碼結果對比

函數作用說明
MidB$(str, pos, len)取位元組陣列片段VB6 字串內部為位元組陣列 (ANSI/DBCS),MidB$ 直接存取位元組
AscB(byte)位元組 → 數值 (0-255)對應 C# (byte)str[pos]
Hex$(num)數值 → 十六進位字串不自動零填補,需手動 If Len=1 Then "0"&
位元組順序高位在前 (Big-Endian)ByteUpper & ByteLower 對應 Unicode code point 高低位元組

重要:VB6 版本實際上是「系統代碼頁位元組 → 十六進位」,非真正 Unicode code point。跨系統遷移時必須確認編碼一致性。

現代 C# 最佳實踐

// .NET Core 2.1+ Span-based 高效能版本
public static string EncodeFast(string s)
{
    var bytes = System.Text.Encoding.Unicode.GetBytes(s); // UTF-16 LE
    return string.Concat(bytes.Chunk(2).Select(chunk => 
        ((ushort)(chunk[1] << 8 | chunk[0])).ToString("X4"))); // 轉 Big-Endian code point
}

總結

C# 以 ushort.ToString("X4") 直接取得 Unicode code point 十六進位,簡潔可靠。VB6 需手動拆解雙位元組並組合,且受系統代碼頁影響。雙向轉換核心在於「固定 4 位十六進位對應單一字元」,C# 版本建議加入 TryParse 防禦性檢查,VB6 版本需注意 ChrW 解碼時的問號歧義 (見下篇)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
字元UnicodeC# EncodeVB6 Encode (ANSI 系統)備註
'3'U+003300330033ASCII 相同
'我'U+62116211取決於系統代碼頁 (可能不同)VB6 依賴 ANSI 代碼頁,非 Unicode 直接轉換