Node.js将64位无符号整数写入缓冲区 [英] nodejs write 64bit unsigned integer to buffer
问题描述
我想以大字节序格式将64位(8字节)大整数存储到nodejs缓冲区对象。
I want to store a 64bit (8 byte) big integer to a nodejs buffer object in big endian format.
此任务的问题是仅nodejs缓冲区支持最大写入32位整数(带有buf.write32UInt32BE(value,offset))。所以我想,为什么我们不能只拆分64位整数?
The problem about this task is that nodejs buffer only supports writing 32bit integers as maximum (with buf.write32UInt32BE(value, offset)). So I thought, why can't we just split the 64bit integer?
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。有人介意显示这两个问题的解决方案吗?
As you see this nearly works. The problem is just splitting the 64bit integer and finding the missing 510 at reading it. Would somebody mind showing the solutions for these two issues?
推荐答案
我认为您正在寻找的是:
I think what you are looking for is:
var bufInt = (buf.readUInt32BE(0) << 8) + buf.readUInt32BE(4);
将第一个数字移位8位并加(而不是乘),直到返回 65535
Shift the first number by 8 bits and add (instead of multiplying), wich returns 65535
EDIT
另一种写方法是:
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将64位无符号整数写入缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!