节点使用缓冲区打包数据

时间:2016-03-22 01:23:46

标签: python node.js buffer

任何人都知道如何在nodejs中转换这个python片段:

return "".join(reversed(struct.pack('I',data)))

我尝试使用Buffer这样在nodejs中做同样的事情:

var buff = new Buffer(4).fill(0);
    buff.writeInt16LE(data, 0);
    return new Buffer(buff.reverse().toString('hex'),'hex');

但是它不能像python片段一样工作,有些数据让我的程序卡住了,它给了我这个错误:

buffer.js:830
    throw new TypeError('value is out of bounds');
    ^

1 个答案:

答案 0 :(得分:0)

确保data是有效的16位有符号整数。这意味着它必须是-32,768到32,767之间的有效整数。

然而,Python的struct.pack()中的'I'用于无符号的32位整数,因此您应该使用的是buff.writeUInt32LE(data, 0)