簡體   English   中英

為什么 String.protoptype.charCodeAt() 可以將二進制字符串轉換為 Uint8Array?

[英]Why String.protoptype.charCodeAt() can convert binary string into an Uint8Array?

假設我有一個 base64 編碼的字符串,我想將它轉換成一個ArrayBuffer ,我可以這樣做:

// base64 decode the string to get the binary data
const binaryString = window.atob(base64EncodedString);

// convert from a binary string to an ArrayBuffer
const buf = new ArrayBuffer(binaryString.length);
const bufView = new Uint8Array(buf);   
for (let i = 0, strLen = binaryString.length; i < strLen; i++) {
    bufView[i] = binaryString.charCodeAt(i);
}

// get ArrayBuffer: `buf`  

String.protoptype.charCodeAt() ,它將返回一個介於 0 和 65535 之間的 integer,表示給定索引處的 UTF-16 代碼單元。 但是Uint8Array的范圍值是 [0, 255]。

我最初認為我們從charCodeAt()獲得的代碼點可能超出Uint8Array范圍的范圍 go。 然后我檢查了內置的atob() function,它返回一個包含解碼數據的ASCII字符串。 根據Binary Array ,ASCII 字符串的范圍是 0 到 127,它包含在Uint8Array的范圍內,這就是我們在這種情況下可以安全使用charCodeAt()的原因。

這是我的理解。 我不確定我是否正確解釋了這一點。 謝謝你的幫助!

所以看起來我的理解是正確的。

感謝@Konrad,這是他/她的補充:

charCodeAt 旨在支持 utf-16。 utf-16 被設計為與 ASCII 兼容,因此前 256 個字符具有與 ASCII 編碼一樣的精確值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM