首先,对于这个愚蠢的问题,我深表歉意,但我是 nodejs 的新手。 我从套接字中读取了一个 64 位小尾数法带符号整数,并将其放在缓冲区中,所以假设我将数字 256 表示为:
<Buffer 00 01 00 00 00 00 00 00>
由于 Buffer 类只有 readInt32LE 和 readUInt32LE,我如何使用 32 位操作将此缓冲区转换为其等效的 js 编号? 我应该读取两个 32 位大端数字然后以某种方式按位还是它们?我应该读他们小端吗?
谢谢
最佳答案
Note that all the positive and negative integers whose magnitude is no greater than 253 are representable in the Number type (indeed, the integer 0 has two representations, +0 and −0).
Javascript 在内部使用 64 位 float ,这意味着您只能准确表示最多 253 或 9007199254740992 的数字。如果您觉得没问题,您可以使用以下代码读取 64 位有符号数/unsigned int 转换为 64 位 float :
function readUInt64(buff, offset) {
return buff.readInt32LE(offset) + 0x100000000*buff.readUInt32LE(offset + 4);
}
function readInt64(buff, offset) {
var word0 = buff.readUInt32LE(offset);
var word1 = buff.readUInt32LE(offset+4);
if (!(word1 & 0x80000000))
return word0 + 0x100000000*word1;
return -((((~word1)>>>0) * 0x100000000) + ((~word0)>>>0) + 1);
}
如果您需要精确表示 - 使用 bignumber.js图书馆
function readUInt64(buff, offset) {
var word0 = buff.readUInt32LE(offset);
var word1 = buff.readUInt32LE(offset+4);
return new BigNumber(word0).plus(new BigNumber(word1).times(0x100000000));
}
关于javascript - 将 64 位小端整数转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17687307/