大网数据广告活动
Web 标准与前端开发

Uint8Array.fromHex()

· 52CE 我爱测

The **`Uint8Array.fromHex()`** static method creates a new Uint8Array object from a hexadecimal string.

The Uint8Array.fromHex() static method creates a new Uint8Array object from a hexadecimal string.

This method parses the string into a byte array. To convert the string into a single number, use the Global_Objects/parseInt function with radix set to 16 instead.

Syntax

Uint8Array.fromHex(string)

Parameters

  • string
    • : A hexadecimal string encoding bytes to convert to a Uint8Array. The string must:
      • Have an even number of characters because two characters encode one byte.
      • Only contain characters in the hexadecimal alphabet, which includes 0–9 and A–F (case-insensitive).
      • Not contain whitespace (unlike Uint8Array.prototype.setFromBase64()).

Return value

A new Uint8Array object containing the decoded bytes from the hexadecimal string.

Exceptions

  • SyntaxError
    • : Thrown if the input string contains characters outside the hex alphabet, or its length is odd.
  • TypeError
    • : Thrown if the input string is not a string.

Examples

Decoding a hexadecimal string

This example decodes a hexadecimal string into a Uint8Array.

const hexString = "cafed00d";
const bytes = Uint8Array.fromHex(hexString);
console.log(bytes); // Uint8Array [ 202, 254, 208, 13 ]

Uppercase characters are also supported:

const hexString = "CAFEd00d";
const bytes = Uint8Array.fromHex(hexString);
console.log(bytes); // Uint8Array [ 202, 254, 208, 13 ]

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。