Search code examples
node.jsbuffer

How can I store an integer in a nodejs Buffer?


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.


Solution

  • 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>
    
    */