potato
potato

Reputation: 3

how to read 2 bytes buffer to double in nodeJS

I am trying to convert the following buffer into a double:

<Buffer 02 00>

And when I try to do buffer.readDoubleLE(0) it returns the following error:

Uncaught RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to write outside buffer bounds

I think that readDoubleLE requires the buffer at least have length 8.
Would it be possible to convert this buffer into a double?

Upvotes: 0

Views: 913

Answers (1)

jfriend00
jfriend00

Reputation: 707318

A double is 8 bytes. You're trying to read 8 bytes from a buffer that contains 2 bytes. You, predictably, get RangeError [ERR_BUFFER_OUT_OF_BOUNDS] when doing that. The Attempt to write outside buffer bounds does not make much sense from what you describe (since your description says you are reading, not writing) so we'd have to see the actual code that generates that error to comment further on that part of the message.

It's not entirely clear what you're really trying to do, but if what you're really trying to do is to read a two byte integer, then you could do this:

let myNumber = buf.readInt16LE(0);

Javascript stores all numbers internally as doubles so myNumber will be usable as a double within Javascript.

Upvotes: 1

Related Questions