Categories
JavaScript Answers Nodejs

How to read a 3 bytes Buffer as an integer with JavaScript and Node.js?

Spread the love

Sometimes, we want to read a 3 bytes Buffer as an integer with JavaScript and Node.js.

In this article, we’ll look at how to read a 3 bytes Buffer as an integer with JavaScript and Node.js.

How to read a 3 bytes Buffer as an integer with JavaScript and Node.js?

To read a 3 bytes Buffer as an integer with JavaScript and Node.js, we can use the readUintBE method.

For instance, we write:

const buffer = Buffer.from('hello world', 'utf8');
const decimal = buffer.readUIntBE(0, 3);
console.log(decimal)

to create a buffer with Buffer.from.

Then we call buffer.readUIntBE with 0 and 3 to read the 3 bytes and convert it into a decimal number.

Therefore, decimal is 6841708.

Conclusion

To read a 3 bytes Buffer as an integer with JavaScript and Node.js, we can use the readUintBE method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *