Uint8Array.prototype.toHex()

基准线 2025
新推出

自 ⁨2025 年 9 月⁩起,此功能适用于最新设备和浏览器版本。此功能可能不适用于较旧的设备或浏览器。

Uint8Array 实例的 toHex() 方法返回一个基于此 Uint8Array 对象数据的十六进制编码字符串。

此方法从字节数组创建字符串。要将单个数字转换为十六进制,请改用将 radix 设置为 16Number.prototype.toString() 方法。

语法

js
toHex()

参数

无。

返回值

一个表示 Uint8Array 中数据的十六进制编码字符串。

示例

编码二进制数据

此示例将 Uint8Array 的数据编码为十六进制字符串。

js
const uint8Array = new Uint8Array([202, 254, 208, 13]);
console.log(uint8Array.toHex()); // "cafed00d"

const data = new Uint8Array([255, 0, 0, 0, 255, 0, 0, 0, 255]);
for (let i = 0; i < data.length; i += 3) {
  console.log(data.slice(i, i + 3).toHex());
}
// "ff0000"
// "00ff00"
// "0000ff"

规范

规范
Uint8Array 与 base64 的相互转换
# sec-uint8array.prototype.tohex

浏览器兼容性

另见