我从后端得到无符号64位整数到ArrayBuffer,由于IEEE 754我不能得到&保持这个序列作为一个数字。有什么办法可以"精简"这个庞大的数字吗?
简而言之:
var buffer = new ArrayBuffer(8);
var raw = new Uint8Array(buffer);
raw[0] = 255;
raw[1] = 255;
raw[2] = 255;
raw[3] = 255;
raw[4] = 255;
raw[5] = 255;
raw[6] = 255;
raw[7] = 255;
var view = new DataView(buffer);
var result = view.getUint64(0); /// :-(
提前感谢。
是的,你可以字符串化Int64,但是没有"内置"的方式来做到这一点,因为就像你说的JavaScript数字是双精度浮点数。
// ...
function readInt64(view){
var small = view.getUint32(0).toString(16); // present as base 16 string
var large = view.getUint32(1).toString(16);
// in a power-of-2 base it's just a string concat to add them
var bigNumber = large + small;
return h2d(bigNumber);
}
其中h2d取自这里的答案
function h2d(s) {
// https://stackoverflow.com/a/12533838/1348195
function add(x, y) {
var c = 0, r = [];
var x = x.split('').map(Number);
var y = y.split('').map(Number);
while(x.length || y.length) {
var s = (x.pop() || 0) + (y.pop() || 0) + c;
r.unshift(s < 10 ? s : s - 10);
c = s < 10 ? 0 : 1;
}
if(c) r.unshift(c);
return r.join('');
}
var dec = '0';
s.split('').forEach(function(chr) {
var n = parseInt(chr, 16);
for(var t = 8; t; t >>= 1) {
dec = add(dec, dec);
if(n & t) dec = add(dec, '1');
}
});
return dec;
}
function readInt64(view, i){
var small = view.getUint32(0 + 2 * i).toString(16); // present as base 16 string
var large = view.getUint32(1 + 2 * i).toString(16);
// in a power-of-2 base it's just a string concat to add them
var bigNumber = large + small;
return h2d(bigNumber);
}
var buffer = new ArrayBuffer(8);
var raw = new Uint8Array(buffer);
raw[0] = 255;
raw[1] = 255;
raw[2] = 255;
raw[3] = 255;
raw[4] = 255;
raw[5] = 255;
raw[6] = 255;
raw[7] = 255;
var view = new DataView(buffer);
var result = readInt64(view, 0);
document.body.innerHTML = result;
下面的DataView.getUint64()
实现将为您提供当前尽可能精确的数值:
如何在JavaScript中从ArrayBuffer/DataView中读取64位整数