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

C# 依區位碼取得中文字元

     編輯:關於C#

前言

區位碼是中文資訊交換碼的編碼方式,每個漢字由兩位區號與兩位位號組成(如 1601 代表「啊」)。本文示範如何在 C# 中透過預設編碼(通常為 Big5/CP950)將區位碼轉換為對應漢字。

區位碼轉換原理

  • 區位碼範圍:區號 16-87,位號 1-94
  • 內碼計算:區號 + 160 (0xA0),位號 + 160 (0xA0)
  • Big5 編碼:高位元組 0xA4-0xF9,低位元組 0x40-0x7E, 0xA1-0xFE

完整實作程式碼


using System;
using System.Text;
using System.Windows.Forms;

public class QuWeiCodeConverter
{
    public string GetCharFromQuWei(string quWeiCode)
    {
        if (string.IsNullOrEmpty(quWeiCode) || quWeiCode.Length != 4)
            throw new ArgumentException("區位碼必須為 4 位數字");

        // 解析區號與位號
        string quStr = quWeiCode.Substring(0, 2);
        string weiStr = quWeiCode.Substring(2, 2);
        
        if (!int.TryParse(quStr, out int qu) || !int.TryParse(weiStr, out int wei))
            throw new ArgumentException("區位碼必須為數字");

        // 計算 Big5 內碼
        int highByte = qu + 160; // 0xA0
        int lowByte = wei + 160; // 0xA0

        // 驗證範圍
        if (highByte < 0xA1 || highByte > 0xF9 || 
            lowByte < 0xA1 || lowByte > 0xFE)
            throw new ArgumentException("區位碼超出有效範圍");

        byte[] bytes = new byte[2];
        bytes[0] = (byte)highByte;
        bytes[1] = (byte)lowByte;

        // 使用預設編碼 (通常為 Big5/CP950) 解碼
        return Encoding.Default.GetString(bytes);
    }
}

WinForms 完整介面範例


public partial class Form1 : Form
{
    private TextBox txtQuWei;
    private TextBox txtResult;
    private Button btnConvert;
    private QuWeiCodeConverter converter = new QuWeiCodeConverter();

    public Form1()
    {
        InitializeComponent();
    }

    private void btnConvert_Click(object sender, EventArgs e)
    {
        try
        {
            string input = txtQuWei.Text.Trim();
            string result = converter.GetCharFromQuWei(input);
            txtResult.Text = result;
        }
        catch (Exception ex)
        {
            MessageBox.Show($"轉換失敗:{ex.Message}", "錯誤", 
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

常見區位碼對照表

字元區位碼區號位號Big5 內碼 (Hex)
啊16011601A4 A1
阿16021602A4 A2
愛16231623A4 B7
中54485448D6 D0
文48864886C0 D6
華28282828BC BC
人34863486C2 D6

編碼環境注意事項

Encoding.Default 行為差異

  • 繁體中文 Windows:通常為 Big5 (CP950)
  • 簡體中文 Windows:通常為 GB2312 (CP936)
  • 英文/其他語系 Windows:可能為 CP1252 (ANSI)
  • .NET Core / .NET 5+:Encoding.Default 固定回傳 UTF-8

跨平台相容寫法


public string GetCharFromQuWeiExplicit(string quWeiCode)
{
    // 明確指定 Big5 編碼,避免環境差異
    Encoding big5 = Encoding.GetEncoding("big5"); // 或 "CP950"
    
    // ... 解析區位碼邏輯同上 ...
    
    return big5.GetString(bytes);
}

反向操作:字元轉區位碼


public string GetQuWeiFromChar(char ch)
{
    Encoding big5 = Encoding.GetEncoding("big5");
    byte[] bytes = big5.GetBytes(new char[] { ch });
    
    if (bytes.Length != 2)
        throw new ArgumentException("非 Big5 雙位元組字元");
    
    int qu = bytes[0] - 160;
    int wei = bytes[1] - 160;
    
    return $"{qu:D2}{wei:D2}";
}

批次轉換工具


public string ConvertQuWeiString(string quWeiString)
{
    if (string.IsNullOrEmpty(quWeiCode) || quWeiString.Length % 4 != 0)
        throw new ArgumentException("區位碼字串長度必須為 4 的倍數");
    
    var sb = new StringBuilder();
    Encoding big5 = Encoding.GetEncoding("big5");
    
    for (int i = 0; i < quWeiString.Length; i += 4)
    {
        string code = quWeiString.Substring(i, 4);
        string quStr = code.Substring(0, 2);
        string weiStr = code.Substring(2, 2);
        
        if (int.TryParse(quStr, out int qu) && int.TryParse(weiStr, out int wei))
        {
            int high = qu + 160;
            int low = wei + 160;
            
            if (high >= 0xA1 && high <= 0xF9 && low >= 0xA1 && low <= 0xFE)
            {
                byte[] bytes = { (byte)high, (byte)low };
                sb.Append(big5.GetString(bytes));
            }
            else
            {
                sb.Append($"[{code}]"); // 標記無效碼
            }
        }
        else
        {
            sb.Append($"[{code}]");
        }
    }
    
    return sb.ToString();
}

現代化替代:Unicode 直接處理

現代應用建議直接使用 Unicode (UTF-8/UTF-16),避免區位碼轉換複雜度:


// 直接使用 Unicode 字元
string text = "中文測試";
char ch = '中'; // U+4E2D
int codePoint = char.ConvertToUtf32(ch.ToString(), 0); // 0x4E2D

// 字串處理皆使用 Unicode,儲存/傳輸使用 UTF-8
byte[] utf8Bytes = Encoding.UTF8.GetBytes(text);
string restored = Encoding.UTF8.GetString(utf8Bytes);

總結

區位碼轉漢字需理解 Big5 編碼結構:高低位元組各加 0xA0 (160) 後以預設編碼解碼。注意 Encoding.Default 在不同作業系統與 .NET 版本行為不同,生產環境建議明確指定 Encoding.GetEncoding("big5")。現代開發應優先採用 Unicode/UTF-8,僅在相容舊系統時處理區位碼轉換。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved