0

I have an array of numbers, which I would like to write to a file using Node.JS.

If I have a number: 256

The file should contain the binary:

`00000001  00000000`

And not:

`00000010  00000101  00000110`

The reason for asking this question is that I have read that the binary string format for buffers is being deprecated1.

1
  • You should include your code. How are you building and writing the buffer which is producing the undesired result? Commented May 27, 2016 at 17:50

2 Answers 2

1

The Buffer class can handle arrays of numbers directly:

// Old style
var buffer = new Buffer([ 150 ]);

// New style
var buffer = Buffer.from([ 150 ]);

// Write the buffer to a file.
// Using `fs.writeFileSync()` just as an example here.
require('fs').writeFileSync('output.bin', buffer);

If you're dealing with larger numbers (not bytes), you need to use a typed array.

For instance, using 16-bit unsigned values:

var array    = [ 5000, 4000 ];
var u16array = Uint16Array.from(array);
var buffer   = new Buffer(u16array.buffer);

require('fs').writeFileSync('output.bin', buffer);
Sign up to request clarification or add additional context in comments.

1 Comment

Any thoughts on writing and reading a double length integer like 256? Right now, its more significant digits are getting chopped off (it shows as 0)
0

Please take a look at Buffer's documention: https://nodejs.org/api/buffer.html

Buffer support read/write binary numbers:

buf.readDoubleBE(offset[, noAssert])
buf.readDoubleLE(offset[, noAssert])
buf.readFloatBE(offset[, noAssert])
buf.readFloatLE(offset[, noAssert])
buf.readInt8(offset[, noAssert])
buf.readInt16BE(offset[, noAssert])
buf.readInt16LE(offset[, noAssert])
buf.readInt32BE(offset[, noAssert])
buf.readInt32LE(offset[, noAssert])
buf.readIntBE(offset, byteLength[, noAssert])
buf.readIntLE(offset, byteLength[, noAssert])
buf.readUInt8(offset[, noAssert])
buf.readUInt16BE(offset[, noAssert])
buf.readUInt16LE(offset[, noAssert])
buf.readUInt32BE(offset[, noAssert])
buf.readUInt32LE(offset[, noAssert])
buf.readUIntBE(offset, byteLength[, noAssert])
buf.readUIntLE(offset, byteLength[, noAssert])

Comments

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.