31

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.

4 Answers 4

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

Note: these API have only recently been made available in the latest stable release of node (<4 days ago). If you're still stuck 0.4, you'll need to loop/bit-twiddle in order to encode integers.
0.5.x was never a stable release. I updated the question to indicate I am on 0.4.x, but have an upvote for an answer that will grow more useful in the future.
Surely this will only write a single byte. What about a 32bit int?
Just wanted to say that as of 2024 new Buffer() is deprecated in favor of Buffer.alloc(). So today's version for a 32bit int would be const buffer = Buffer.alloc(8); outputBuffer.writeInt32BE(943954791); This answer shows other ways to initialize a Buffer: stackoverflow.com/a/52257416/10044295
12

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

Comments

2

Since it's not builtin 0.4.12 you could use something like this:

var integer = 1000;
var length = Math.ceil((Math.log(integer)/Math.log(2))/8); // How much byte to store integer in the buffer
var buffer = new Buffer(length);
var arr = []; // Use to create the binary representation of the integer

while (integer > 0) {
    var temp = integer % 2;
    arr.push(temp);
    integer = Math.floor(integer/2);
}

console.log(arr);

var counter = 0;
var total = 0;

for (var i = 0,j = arr.length; i < j; i++) {
   if (counter % 8 == 0 && counter > 0) { // Do we have a byte full ?
       buffer[length - 1] = total;
       total = 0;
       counter = 0;
       length--;      
   }

   if (arr[i] == 1) { // bit is set
      total += Math.pow(2, counter);
   }
   counter++;
}

buffer[0] = total;

console.log(buffer);


/* OUTPUT :

racar $ node test_node2.js 
[ 0, 0, 0, 1, 0, 1, 1, 1, 1, 1 ]
<Buffer 03 e8>

*/

Comments

0

This is something very efficient but uses some "bit twiddling"

// Filled 8 bits number
const fillByte = 0xff;
function bufferFromInt(num){
    const buffArr = [];
    do {
        buffArr.push(fillByte & num);
    } while(num >>= 8);
    return Buffer.from(buffArr.reverse())
}

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.