javascript - 在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 并用它做一些有意义的事情。
解决方案
就像 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
推荐阅读
- javascript - 如何将功能从客户端传递到服务器(nodejs)
- oracle-sqldeveloper - 双击日期字段应显示当前日期
- elixir - 如何为 has_one / belongs_to_many 关联定义 Elixir Ecto 模式?
- python - 在 For 循环中使用字典值的大写测验
- python - 在 Pandas 中获取工作日时出错
- python - 错误:给出双重要求:Pillow==6.1.0(来自 -r requirements.txt(第 25 行))
- python - 摆脱熊猫中的重复行
- algorithm - 关键词云是如何构建的?
- apache - Apache2 配置到 Nginx 配置?
- laravel - 将laravel部署到heroku时,参数“client_encoding”的值无效:“utf8mb4”(SQL:从“tablename”中选择*)