Uint8Array.prototype.setFromHex()

基準線 2025
新推出

自 ⁨2025 年 9 月⁩起,此功能適用於最新裝置和瀏覽器版本。此功能可能不適用於較舊的裝置或瀏覽器。

Uint8Array 例項的 setFromHex() 方法使用十六進位制編碼字串中的位元組填充此 Uint8Array 物件,並返回一個指示讀取和寫入了多少位元組的物件。

此方法會將字串解析為位元組陣列。要將字串轉換為單個數字,請改用 radix 設定為 16parseInt() 函式。

語法

js
setFromHex(string)

引數

string

要寫入 Uint8Array 的位元組的十六進位制字串編碼。該字串必須

  • 具有偶數個字元,因為兩個字元編碼一個位元組。
  • 僅包含十六進位制字母表中的字元,其中包括 0-9 和 A-F(不區分大小寫)。
  • 不包含空格(與 Uint8Array.prototype.setFromBase64() 不同)。

請注意,字串僅讀取到陣列填滿為止,因此此後任何無效的十六進位制語法都將被忽略。

返回值

包含以下屬性的物件:

read

從輸入字串中讀取的十六進位制字元數。如果解碼後的資料適合陣列,則它等於輸入字串的長度;否則,它等於適合陣列的完整十六進位制字元數。

written

寫入 Uint8Array 的位元組數。永遠不會大於此 Uint8ArraybyteLength

異常

SyntaxError

如果輸入字串包含十六進位制字母表之外的字元,或者其長度為奇數,則會丟擲此錯誤。

TypeError

如果輸入字串不是字串,則會丟擲此錯誤。

示例

解碼十六進位制字串

此示例將十六進位制字串解碼到現有的 Uint8Array 中。

js
const uint8Array = new Uint8Array(8);
const result = uint8Array.setFromHex("cafed00d");
console.log(result); // { read: 8, written: 4 }
console.log(uint8Array); // Uint8Array(8) [202, 254, 208, 13, 0, 0, 0, 0]

將大字串解碼到小陣列中

如果字串包含的資料多於陣列可容納的數量,則該方法將只寫入陣列可容納的位元組數。

js
const uint8Array = new Uint8Array(4);
const result = uint8Array.setFromHex("cafed00d-some random stuff");
console.log(result); // { read: 8, written: 4 }
console.log(uint8Array); // Uint8Array(4) [202, 254, 208, 13]

多餘的字元將被忽略,即使它們是無效的。但是,輸入字串的總長度必須是偶數。

在特定偏移量設定資料

setFromHex() 方法始終從 Uint8Array 的開頭開始寫入。如果要寫入陣列中間,則可以改用 TypedArray.prototype.subarray() 寫入。

js
const uint8Array = new Uint8Array(8);
// Start writing at offset 2
const result = uint8Array.subarray(2).setFromHex("cafed00d");
console.log(result); // { read: 8, written: 4 }
console.log(uint8Array);
// Uint8Array(8) [0, 0, 202, 254, 208, 13, 0, 0]

規範

規範
Uint8Array 與 base64 的相互轉換
# sec-uint8array.prototype.setfromhex

瀏覽器相容性

另見