candu / node-int64-native

A simple uint64_t wrapper for node.js.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Write to a buffer

bjackson opened this issue · comments

How would I write and read a 64-bit integer to and from node buffer?

Good question!

Right now, the best way would be something like

Buffer.prototype.writeUInt64BE = function(value, offset, noAssert) {
  this.writeUInt32BE(value.high32(), offset, noAssert);
  this.writeUInt32BE(value.low32(), offset + 4, noAssert);
};
Buffer.prototype.writeUInt64LE = function(value, offset, noAssert) {
  this.writeUInt32LE(value.low32(), offset, noAssert);
  this.writeUInt32LE(value.high32(), offset + 4, noAssert);
};

with the following usage:

var buf = new Buffer(8);
var x = new Int64('0xfedcba9876543210');
buf.writeUInt64BE(x, 0);

Alternatively: if you were hoping for Int64.prototype.writeToBufferBE(buf, offset), feel free to submit a pull request!

Thanks so much!

Is there an easy way to read from the buffer? Is there an interface to directly access the bits?

I'll see if I can write that function. I'm doing this at work and I'd have to check with the boss to make sure I can contribute to an open source repo.