bod*_*ser 9 buffer byte integer node.js
我想以big endian格式将64位(8字节)大整数存储到nodejs缓冲区对象.
关于此任务的问题是nodejs缓冲区仅支持将32位整数写为最大值(使用buf.write32UInt32BE(value,offset)).所以我想,为什么我们不能只拆分64位整数?
var buf = new Buffer(8);
buf.fill(0) // clear all bytes of the buffer
console.log(buf); // outputs <Buffer 00 00 00 00 00 00 00 00>
var int = 0xffff; // as dezimal: 65535
buf.write32UInt32BE(0xff, 4); // right the first part of the int
console.log(buf); // outputs <Buffer 00 00 00 00 00 00 00 ff>
buf.write32UInt32BE(0xff, 0); // right the second part of the int
console.log(buf); // outputs <Buffer 00 00 00 ff 00 00 00 ff>
var bufInt = buf.read32UInt32BE(0) * buf.read32UInt32BE(4);
console.log(bufInt); // outputs 65025
Run Code Online (Sandbox Code Playgroud)
如你所见,这几乎可行.问题只是拆分64位整数并在读取时找到丢失的510.有人会介意为这两个问题展示解决方案吗?
Cha*_*had 11
我认为你在寻找的是:
var bufInt = (buf.readUInt32BE(0) << 8) + buf.readUInt32BE(4);
Run Code Online (Sandbox Code Playgroud)
将第一个数字移动8位并添加(而不是相乘),返回 65535
编辑
另一种写作方式是:
var buf = new Buffer(8);
buf.fill(0);
var i = 0xCDEF; // 52719 in decimal
buf.writeUInt32BE(i >> 8, 0); //write the high order bits (shifted over)
buf.writeUInt32BE(i & 0x00ff, 4); //write the low order bits
console.log(buf); //displays: <Buffer 00 00 00 cd 00 00 00 ef>
var bufInt = (buf.readUInt32BE(0) << 8) + buf.readUInt32BE(4);
console.log(bufInt); //displays: 52719
Run Code Online (Sandbox Code Playgroud)