我想以大端格式将 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
正如你所看到的,这几乎有效。问题只是拆分 64 位整数并在读取它时找到丢失的 510。有人会介意展示这两个问题的解决方案吗?
最佳答案
我认为你正在寻找的是:
var bufInt = (buf.readUInt32BE(0) << 8) + buf.readUInt32BE(4);
将第一个数字移位 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
关于node.js - nodejs 将 64 位无符号整数写入缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14730980/