【问题标题】:Reading UINT 128 from Node JS Buffer从 Node JS 缓冲区读取 UINT 128
【发布时间】:2019-12-08 04:54:57
【问题描述】:
我正在编写一个 Node JS 客户端,它正在向第三方服务器查询信息。我从第三方服务器收到的部分消息是 UINT 128(在文档中指定)。但是,据我所知,NodeJS 缓冲区不支持从缓冲区读取 128 位整数。我检查了this page 和两个最有可能的函数(读取 BIGITS 和读取未指定的字节长度整数)都不支持 128 位整数。
我已经尝试安装和使用big-integer 模块,但如果这是正确的方法,我无法理解如何将字节从缓冲区读取到一个大整数对象中。
如何从 NodeJS 缓冲区中读取 UINT128?如有必要,我愿意使用位算术,但我不确定如何。
【问题讨论】:
标签:
node.js
buffer
int128
【解决方案1】:
我通过在 DataView 上使用 getBigUint64 两次,然后在两者上调用 toString,连接字符串并将该字符串解析为 BigInt 来做到这一点......这很愚蠢,但它似乎有效。您也可以使用按位运算符连接 64 位 BigInts,但我没有尝试过。
readUInt128() {
let a = this.readUInt64();
let b = this.readUInt64();
return BigInt(a.toString() + b.toString());
}
readUInt64() {
let result = this.view.getBigUint64(this.pos, this.littleEndian)
this.pos += 8
return result
}