專案遇到 Unicode 轉 GBK 失敗,罕用字變為 ??。需建立完整對照表輔助排查與轉碼。
String,再用 getBytes("Unicode") 取得 Unicode 位元組。
int count = 0;
for (int seg = 0xB0; seg <= 0xF7; seg++) {
for (int ch = 0xA1; ch <= 0xFE; ch++) {
byte[] gbkBytes = new byte[] {(byte)seg, (byte)ch};
String str = new String(gbkBytes, "GBK");
byte[] unicodeBytes = str.getBytes("Unicode"); // 長度 4
if (unicodeBytes.length == 4) {
count++;
StringBuffer buf = new StringBuffer();
for (byte b : gbkBytes) buf.append((b & 0xFF) + " ");
// Unicode 位元組為 Little Endian,倒序讀取
for (int i = 3; i > 1; i--) buf.append((unicodeBytes[i] & 0xFF) + " ");
buf.append("\n");
osw.write(buf.toString());
}
}
}
說明:
getBytes("Unicode") 回傳 4 位元組:前兩個為 BOM/結構資訊,後兩個為實際碼點,且為 Little Endian 順序(低位在前)。GB高位 GB低位 Unicode低位 Unicode高位。讀入檔案,以 GB 碼為索引建立陣列/Map,即可快速查詢 Unicode 碼點,輔助轉碼邏輯驗證與除錯。