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.
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.
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.
The write() method writes the specified string into a buffer, at the specified position.
var buf = new Buffer(4); buf.writeUInt8(0x3, 0);
http://nodejs.org/docs/v0.6.0/api/buffers.html#buffer.writeUInt8
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With