Uint8Array(8) 字符串化

Uint8Array(8) stringification

我正在从后端获取无符号的 64 位整数到 ArrayBuffer 中,由于 IEEE 754,我无法将此序列作为数字获取和保存。 "stringify"这个庞大的数字有什么办法吗?

简而言之:

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 字符串化,但是没有 "built in" 方法可以做到这一点,因为正如您所说 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 取自 this answer here

function h2d(s) {
    // 
    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() 实现将为您提供当前尽可能精确的数值:

How to Read 64-bit Integer from an ArrayBuffer / DataView in JavaScript