中文字元在不同編碼下位元組長度不同:
? (0x3F),資訊遺失**「字串長度」無絕對答案,必須指定編碼。**
public static int GetByteLength(string text, Encoding encoding = null) {
if (string.IsNullOrEmpty(text)) return 0;
encoding ??= Encoding.UTF8; // 預設 UTF-8
return encoding.GetByteCount(text);
}
// 使用範例
string s = "I Love 北京!";
Console.WriteLine($"UTF-8: {GetByteLength(s, Encoding.UTF8)}"); // 13
Console.WriteLine($"UTF-16: {GetByteLength(s, Encoding.Unicode)}"); // 24 (含 BOM 需 -2)
Console.WriteLine($"GBK: {GetByteLength(s, Encoding.GetEncoding("gb2312"))}"); // 14
Console.WriteLine($"Default(ANSI): {GetByteLength(s, Encoding.Default)}"); // 視系統地區而定
某些舊系統/通訊協定定義「中文佔 2 字節、英文/數字/符號佔 1 字節」,不對應任何標準編碼,需自行實作:
public static int GetLegacyByteLength_AsciiCheck(string s) {
if (string.IsNullOrEmpty(s)) return 0;
var ascii = Encoding.ASCII.GetBytes(s); // 中文變 0x3F ('?')
int len = 0;
foreach (byte b in ascii) {
len += (b == 0x3F) ? 2 : 1; // 簡單假設:所有非 ASCII 字元視為中文佔 2 字節
}
return len;
}
⚠️ **缺陷**:任何非 ASCII 字元 (日文、韓文、Emoji、特殊符號) 都會被算作 2 字節,不準確。
public static int GetLegacyByteLength_UnicodeAnalysis(string s) {
if (string.IsNullOrEmpty(s)) return 0;
byte[] bytes = Encoding.Unicode.GetBytes(s); // Little-Endian UTF-16
int len = 0;
for (int i = 0; i < bytes.Length; i++) {
if (i % 2 == 0) { // 低位元組 (每個 char 的第一個 byte)
len++; // 基礎 1 字節
} else { // 高位元組
if (bytes[i] > 0) len++; // 高位非零 → 非 ASCII 範圍 → 視為雙字節字元
}
}
return len;
}
原理:UTF-16 LE 中,ASCII 字元高位元組為 0x00;非 ASCII (含中文) 高位元組非零。
| 業務標準 | 實作方式 |
|---|---|
| GBK/GB2312 | Encoding.GetEncoding("gb2312").GetByteCount(s) |
| Big5 | Encoding.GetEncoding("big5").GetByteCount(s) |
| UTF-8 | Encoding.UTF8.GetByteCount(s) |
| 自定義 (中文2/英文1) | 遍歷 char,char.IsSurrogatePair 處理補充平面,char.GetUnicodeCategory 判斷類別 |