8

I get this buffer from my serial port:

<Buffer 04 02 08 dc>

The 2nd byte says how many bytes do I need to parse my from response data. So I need to parse these two bytes 08 dc, and convert them to long unsigned.

How do I do it in JavaScript on a Node.js server?

5
  • Are they big- or little-endian? (i.e. do you want 0x08dc or 0xdc08?) What’s the highest possible number of bytes? (If long = 8 bytes, note that JavaScript can’t represent those precisely without a BigInt.) Commented Jun 11, 2019 at 15:31
  • 2
    Anyway, read around here: nodejs.org/api/… Commented Jun 11, 2019 at 15:32
  • @Ry- thx for the answer, however I rly dont know if they are BE or LE, i've looking at the API before I post this :/, any Idea how to find this? It should be some specification? Commented Jun 11, 2019 at 15:35
  • Also using the nodejs API to convert these buffers, it gives me weird numbers, for example its not possible for that i'm reading an instante voltages of 2280 volts, when the maximum voltage in my country is 220v Commented Jun 11, 2019 at 15:40
  • There is no such thing as "long unsigned" in JavaScript. What are you gonna do with the integer? It might be better to keep them in the buffer. Commented Jun 11, 2019 at 15:51

1 Answer 1

11

buf.readInt32BE([offset]) and buf.readInt32LE([offset]) let you read a 32b int from 4-bytes starting at offset.

Reads a signed 32-bit integer from buf at the specified offset with the specified endian format (readInt32BE() returns big endian, readInt32LE() returns little endian).

Integers read from a Buffer are interpreted as two's complement signed values.

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

2 Comments

Thank you. I've read the docs, and everything you said was correct, I've just miss-understood the docs of my power meter.
@bmvr, I'm glad you've got it sorted. There are variants that take a byteLength argument which might work with your "2nd byte says ..." requirement, though not for byteLengths > 6 because JavaScript uses floating point numbers with a 52b mantissa.

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.