如何在Node.js的缓冲区中存储整数?

29

Node.js的Buffer非常不错。但是,它似乎更适合存储字符串。构造函数可以接受一个字符串、一个字节数组或要分配的字节数。

我正在使用Node.js 0.4.12版本,想在缓冲区中存储一个整数。不是integer.toString(),而是整数的实际字节。有没有一种简单的方法可以做到这一点,而无需循环整数并进行一些位操作?我可以这样做,但我觉得这是其他人可能曾经面对过的问题。

4个回答

50

1
注意:这些 API 只在最新稳定版本的 Node.js 中(<4 天前)才可用。如果您仍停留在 0.4 版本,则需要循环/位操作来编码整数。 - wulong
0.5.x从未是一个稳定的版本。我更新了问题,表明我在使用0.4.x,但如果有答案能够在未来变得更加有用,我会给予点赞。 - Jamison Dance
1
这肯定只会写入一个字节。那么32位的整数呢? - Mike M

10

使用较新版本的Node更加容易。以下是一个2字节无符号整数的示例:

let buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(1234);  // Big endian

或者对于一个4字节的有符号整数:

let buf = Buffer.allocUnsafe(4);  // Init buffer without writing all data to zeros
buf.writeInt32LE(-123456);  // Little endian this time..

不同的 writeInt 函数是在 Node v0.5.5 中添加的。

查看这些文档以获得更好的理解:
Buffer
writeUInt16BE/LE
writeUIntBE/LE
allocUnsafe


2

由于在0.4.12中没有内置此功能,您可以尝试使用以下类似方法:

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>

*/

0
这是一种非常高效的方法,但使用了一些“位操作”。
// 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())
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接