Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store an integer in a nodejs Buffer?

Tags:

The nodejs Buffer is pretty swell. However, it seems to be geared towards storing strings. The constructors either take a string, an array of bytes, or a size of bytes to allocate.

I am using version 0.4.12 of Node.js, and I want to store an integer in a buffer. Not integer.toString(), but the actual bytes of the integer. Is there an easy way to do this without looping over the integer and doing some bit-twiddling? I could do that, but I feel like this is a problem someone else must have faced at some time.

like image 216
jergason Avatar asked Nov 08 '11 00:11

jergason


People also ask

How does the buffer store data in node JS?

A buffer is a space in memory (typically RAM) that stores binary data. In Node. js, we can access these spaces of memory with the built-in Buffer class. Buffers store a sequence of integers, similar to an array in JavaScript.

What is buffer data type in node JS?

The Buffer class in Node. js is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data.

Which method is used for writing to buffer in Node JS?

The write() method writes the specified string into a buffer, at the specified position.


2 Answers

var buf = new Buffer(4); buf.writeUInt8(0x3, 0); 

http://nodejs.org/docs/v0.6.0/api/buffers.html#buffer.writeUInt8

like image 132
Chris Biscardi Avatar answered Oct 05 '22 18:10

Chris Biscardi


With more recent versions of Node this is much easier. Here's an example for a 2 byte unsigned integer:

let buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(1234);  // Big endian 

Or for a 4 byte signed integer:

let buf = Buffer.allocUnsafe(4);  // Init buffer without writing all data to zeros buf.writeInt32LE(-123456);  // Little endian this time.. 

The different writeInt functions were added in node v0.5.5.

Have a look at these docs for a better understanding:
Buffer
writeUInt16BE/LE
writeUIntBE/LE
allocUnsafe

like image 32
MattCochrane Avatar answered Oct 05 '22 17:10

MattCochrane