1

I have a hex buffer in Node js like this:

buffer <00 E0>

I need to convert to int using little endianess. So I would read E0 00 -> 57344

For the moment I use this method:

var str = "0x" + buffer [i] .toString ('16 '). toString + buffer [i-1] .toString ('16'). toString to convert to string

var result = parseInt (str).

This method works but sometimes I get errors like this: buffer [0] = 00 but I receve 0 instead 00 or 1 instead to 01 or 10,

Is there another way to get this convertons or to solve this problem?

Thank you

1 Answer 1

1

Consider using the Buffer.readInt*LE or Buffer.readUInt*LE methods (the * stands for the integer size, LE for little endian). Taking your code as an example, you can use Buffer.readIntLE:

Buffer.from([ 0x00, 0xe0]).readUIntLE(0, 2)

If you have a variable buffer size:

var buffer = Buffer.from(bytes);
var result = buffer.readUIntLE(0, bytes.length) // assumes bytes.length is even
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I tried this method and its work, but reading doc:" Reads byteLength number of bytes from buf at the specified offset and interprets the result as an unsigned, little-endian integer supporting up to 48 bits of accuracy." When I have a want read a number of byte < 6 its works but when I need to convert a number of bytes > 6 (128 forx example) doesn't work. How can I convert it? Thanks
You asked about working with an integer, so I assumed 32 bits. You can read a 64 bits buffer by using readBigInt64LE instead. More than that is not an integer anymore, so you'd need a more involved code.
Yes! In this cases I must convert to String. I read and covert to Integer before (using readUIntLE) and then I use fromCharCode(int) to get a String. Thanks!!

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.