跳至內容
Astera Technology

AB 匯出為何解成另一組字?

依已訂 UTF-16 字節次序解碼,聲明矛盾或字節不足便暫停。

下載完整個案資料及參考答案 ↓

先核來源與已訂規則

這份假設檔案約定 UTF-16LE,每組兩字節須完整。41 00 42 00 在此是 AB,當作 BE 就變字。本例先核檔案聲明及雙數字節,不自行估次序。

已填假設輸入
紀錄輸入 JSON
原例輸入{"encoding":"utf-16le","bytes":[65,0,66,0]}
下載可編輯 CSV ↓

比較兩條實際路徑

更正為 AB。此檔案若聲明 BE 要停,是本例格式約定,並不表示 BE 編碼本身無效。

錯誤與更正路徑的輸出
路徑輸出 JSON
錯誤路徑{"accepted":true,"text":"䄀䈀"}
更正路徑{"accepted":true,"text":"AB"}
下載可編輯 CSV ↓
本地 Node.js 程序:22.23.3 或 24.14.1
import {DatabaseSync} from 'node:sqlite';
import {TextDecoder} from 'node:util';
import {inflateSync} from 'node:zlib';
import {posix} from 'node:path';
import {createHash} from 'node:crypto';
const rows=(db,sql)=>db.prepare(sql).all().map(r=>({...r}));
const failed=(action)=>{try{action();return null;}catch(e){return {code:e.errcode??e.code??e.name};}};

import assert from 'node:assert/strict';
const run=function run(i,corrected=true){
    if(corrected&&(i.encoding!=='utf-16le'||i.bytes.length%2!==0))return {accepted:false,error:'encoding-contract'};
    try{return {accepted:true,text:new TextDecoder(corrected?i.encoding:'utf-16be',{fatal:true}).decode(Uint8Array.from(i.bytes))};}
    catch{return {accepted:false,error:'invalid-encoded-text'};}
  };
const cases=[{"label":"misleading base","input":{"encoding":"utf-16le","bytes":[65,0,66,0]},"expected":{"accepted":true,"text":"䄀䈀"},"corrected":false},{"label":"corrected base","input":{"encoding":"utf-16le","bytes":[65,0,66,0]},"expected":{"accepted":true,"text":"AB"},"corrected":true},{"label":"contradictory declaration","input":{"encoding":"utf-16be","bytes":[65,0]},"expected":{"accepted":false,"error":"encoding-contract"},"corrected":true},{"label":"odd trailing byte","input":{"encoding":"utf-16le","bytes":[65]},"expected":{"accepted":false,"error":"encoding-contract"},"corrected":true}];
for(const test of cases){
  const actual=run(test.input,test.corrected);
  assert.deepEqual(actual,test.expected,test.label);
  console.log(test.label,actual);
}
下載可執行例子 ↓

下次載入前核邊界

聲明不符與只剩單字節,兩者都在收紀錄前擋住。

可編輯邊界紀錄及預期輸出
情況輸入 JSON預期輸出 JSON
字節次序聲明相反{"encoding":"utf-16be","bytes":[65,0]}{"accepted":false,"error":"encoding-contract"}
不足一組字節{"encoding":"utf-16le","bytes":[65]}{"accepted":false,"error":"encoding-contract"}
下載可編輯 CSV ↓

次序錯但看似有字,可否照匯入?

查看參考答案

不可,有字不等於依正確編碼。此來源須 LE 及完整字節組,結果應 AB。

相關資源