将 Uint8Array 转换为等价于 node.js 的十六进制字符串

Convert Uint8Array into hex string equivalent in node.js

我正在使用 node.js v4.5。假设我有这个 Uint8Array 变量。

var uint8 = new Uint8Array(4);
uint8[0] = 0x1f;
uint8[1] = 0x2f;
uint8[2] = 0x3f;
uint8[3] = 0x4f;

这个数组可以是任意长度,但我们假设长度是 4。

我想要一个将 uint8 转换为等效的十六进制字符串的函数。

var hex_string = convertUint8_to_hexStr(uint8);
//hex_string becomes "1f2f3f4f"

您可以使用 Buffer.from() and subsequently use toString('hex'):

let hex = Buffer.from(uint8).toString('hex');

另一个解决方案:

将 int8 转换为 hex 的基本函数:

// padd with leading 0 if <16
function i2hex(i) {
  return ('0' + i.toString(16)).slice(-2);
}

reduce:

uint8.reduce(function(memo, i) {return memo + i2hex(i)}, '');

mapjoin

Array.from(uint8).map(i2hex).join('');

Buffer.from 有多个覆盖。

如果直接用您的 uint8 调用它,它会不必要地 复制 它的内容,因为它选择 Buffer.from( <Buffer|Uint8Array> ) 版本。

您应该调用 Buffer.from( arrayBuffer[, byteOffset[, length]] ) 版本,它不会复制,只会创建缓冲区的 视图

let hex = Buffer.from(uint8.buffer,uint8.byteOffset,uint8.byteLength).toString('hex');