admin管理员组

文章数量:1245847

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?

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?

Share Improve this question edited Jun 11, 2019 at 15:30 Ry- 225k56 gold badges492 silver badges498 bronze badges asked Jun 11, 2019 at 15:27 bmvrbmvr 8763 gold badges10 silver badges26 bronze badges 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.) – Ry- Commented Jun 11, 2019 at 15:31
  • 2 Anyway, read around here: nodejs/api/… – Ry- 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? – bmvr 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 – bmvr 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. – Bergi Commented Jun 11, 2019 at 15:51
Add a ment  | 

1 Answer 1

Reset to default 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 plement signed values.

本文标签: nodejsConvert Buffer to integer in JavaScriptStack Overflow