如何在 nodejs 缓冲区中存储整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8044543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:44:42  来源:igfitidea点击:

How can I store an integer in a nodejs Buffer?

node.jsbuffer

提问by jergason

The nodejs Bufferis 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.

nodejsBuffer非常膨胀。然而,它似乎是为了存储字符串。构造函数采用字符串、字节数组或要分配的字节大小。

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.

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

采纳答案by malletjo

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

由于它不是内置的 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>

*/

回答by MattCochrane

With more recent versions of Node this is much easier. Here's an example for a 2 byte unsigned integer:

使用更新版本的 Node,这要容易得多。下面是一个 2 字节无符号整数的例子:

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

Or for a 4 byte signed integer:

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

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

The different writeIntfunctions were added in node v0.5.5.

writeInt节点 v0.5.5 中添加了不同的功能。

Have a look at these docs for a better understanding:
Buffer
writeUInt16BE/LE
writeUIntBE/LE
allocUnsafe

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