Reputation: 1160
Background
I am attempting to iterate over a buffer object which basically contains hex values. That is perfect for me as each hex value is something I need to decode. However when I loop through the array they get converted to decimal values. How can I loop through it without the values getting converted?
My code
console.log(encoded)
const buf = Buffer.from(encoded)
for (const item of buf) {
console.log(item)
}
Some of my output
<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
...
The original output <Buffer 0c 00 ......
is desired as I can for instance take each output like 0c and do something meaningful with it.
Upvotes: 4
Views: 10147
Reputation: 451
Like T.J. mentioned in his answer, you probably want the numbers. But, if you do need the numbers formatted like you say you can do something like this:
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
Upvotes: 5
Reputation: 1075209
They aren't getting converted, they're numbers. Hex vs. decimal is how you write a number, but the number is the same regardless. It's just that when you console.log
a buffer, it shows you its contents using hex. But when you output them individually, you're using console.log
, which uses the default number => string (decimal). They're just numbers either way.
If you need those numbers as hex strings, you can use item.toString(16)
, but I suspect you want them as numbers, in which case just use item
.
Upvotes: 7