首页 > 解决方案 > 在javascript中循环缓冲区

问题描述

背景

我试图迭代一个基本上包含十六进制值的缓冲区对象。这对我来说是完美的,因为每个十六进制值都是我需要解码的。但是,当我遍历数组时,它们会转换为十进制值。如何在不转换值的情况下循环遍历它?

我的代码

  console.log(encoded)
  const buf = Buffer.from(encoded)
  for (const item of buf) {
    console.log(item)
  }

我的一些输出

<Buffer 0c 00 00 00 99 4e 98 3a f0 9d 09 3b 00 00 00 00 68 48 12 3c f0 77 1f 4a 6c 6c 0a 4a 0f 32 5f 31 31 39 38 36 31 5f 31 33 33 39 33 39 40 fc 11 00 09 00 ... 336 more bytes>
12
0
0
0
153
78
152
58
240
157
9
...

需要原始输出<Buffer 0c 00 ......,因为我可以例如获取每个输出,例如 0c 并用它做一些有意义的事情。

标签: javascriptnode.js

解决方案


就像 TJ 在他的回答中提到的那样,您可能想要这些数字。但是,如果您确实需要像您说的那样格式化的数字,您可以执行以下操作:

function* hexFormatValues(buffer) {
  for (let x of buffer) {
    const hex = x.toString(16)
    yield hex.padStart(2, '0')
  }
}

const buf = Buffer.from([12, 0, 0, 0, 153, 78, 152, 58, 240, 157, 9])

for (let hex of hexFormatValues(buf)) {
  console.log(hex)
} 

// 0c 00 00 00 99 4e 98 3a f0 9d 09

推荐阅读