4

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.

2
  • "That is perfect for me as each hex value is something i need to decode." Decode how? Commented Feb 11, 2020 at 17:12
  • You can get it's representation as a string using yourNumber.toString(16); Commented Feb 11, 2020 at 17:22

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I asked a new question that you may be able to help with stackoverflow.com/questions/60214048/…
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.