![](/img/trans.png)
[英]Javascript: converting binary data in Uint8Array to string corrupting file
[英]Converting from a Uint8Array to a string and back
我在從特定的 Uint8Array 轉換為字符串並返回時遇到問題。 我在瀏覽器和 Chrome 中工作,它本機支持 TextEncoder/TextDecoder 模塊。
如果我從一個簡單的案例開始,一切似乎都運行良好:
const uintArray = new TextEncoder().encode('silly face demons'); // Uint8Array(17) [115, 105, 108, 108, 121, 32, 102, 97, 99, 101, 32, 100, 101, 109, 111, 110, 115] new TextDecoder().decode(uintArray); // silly face demons
但是下面的案例並沒有給我我期望的結果。 在不涉及太多細節(它與密碼學相關)的情況下,讓我們從提供以下 Uint8Array 的事實開始:
Uint8Array(24) [58, 226, 7, 102, 202, 238, 58, 234, 217, 17, 189, 208, 46, 34, 254, 4, 76, 249, 169, 101, 112, 102, 140, 208]
我想要做的是將其轉換為字符串,然后將字符串解密回原始數組,但我得到了這個:
const uintArray = new Uint8Array([58, 226, 7, 102, 202, 238, 58, 234, 217, 17, 189, 208, 46, 34, 254, 4, 76, 249, 169, 101, 112, 102, 140, 208]); new TextDecoder().decode(uint8Array); // :�f��:����."�L��epf�� new TextEncoder().encode(':�f��:����."�L��epf��');
...導致: Uint8Array(48) [58, 239, 191, 189, 7, 102, 239, 191, 189, 239, 191, 189, 58, 239, 191, 189, 239, 191, 189, 17, 239, 191, 189, 239, 191, 189, 46, 34, 239, 191, 189, 4, 76, 239, 191, 189, 239, 191, 189, 101, 112, 102, 239, 191, 189, 239, 191, 189]
數組增加了一倍。 編碼有點超出我的駕駛室。 誰能告訴我為什么數組翻了一番(我假設它是原始數組的替代表示......?)。 另外,更重要的是,有沒有辦法讓我回到原來的數組(即把我得到的數組加倍)?
您嘗試將數組中的代碼點轉換為沒有意義或不允許的utf-8
。 幾乎所有>= 128
的東西都需要特殊處理。 其中一些是允許的,但它們是多字節序列的前導字節,而有些像254
是不允許的。 如果你想來回轉換,你需要確保你正在創建有效utf-8
。 這里的代碼頁布局可能很有用: https ://en.wikipedia.org/wiki/UTF-8#Codepage_layout 非法字節序列的描述: https ://en.wikipedia.org/wiki/UTF-8#無效字節序列。
作為一個具體的例子,這個:
let arr = new TextDecoder().decode(new Uint8Array([194, 169]))
let res = new TextEncoder().encode(arr) // => [194, 168]
有效,因為[194, 169]
對於 © 是有效的 utf-8,但是:
let arr = new TextDecoder().decode(new Uint8Array([194, 27]))
let res = new TextEncoder().encode(arr) // => [239, 191, 189, 27]
不是因為它不是一個有效的序列。
從Uint8Array
獲取字符串並返回:
var u8arr = new Uint8Array([34, 128, 255]);
var u8str = u8arr.toString(); // Convert Uint8Array to String
console.log(u8str);
var u8arr2 = Uint8Array.from(u8str.split(',').map(x=>parseInt(x,10)));
console.log(u8arr2); // back to Uint8Array
這不會受到 utf-8 問題的影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.