Extracting the exponent and mantissa of a Javascript Number

后端 未结 8 658
执笔经年
执笔经年 2020-12-03 03:03

Is there a reasonably fast way to extract the exponent and mantissa from a Number in Javascript?

AFAIK there\'s no way to get at the bits behind a Number in Javascri

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 03:49

    Using the new ArrayBuffer access arrays, it is actually possible to retrieve the exact mantissa and exponent, by extracting them from the Uint8Array. If you need more speed, consider reusing the Float64Array.

    function getNumberParts(x)
    {
        var float = new Float64Array(1),
            bytes = new Uint8Array(float.buffer);
    
        float[0] = x;
    
        var sign = bytes[7] >> 7,
            exponent = ((bytes[7] & 0x7f) << 4 | bytes[6] >> 4) - 0x3ff;
    
        bytes[7] = 0x3f;
        bytes[6] |= 0xf0;
    
        return {
            sign: sign,
            exponent: exponent,
            mantissa: float[0],
        }
    }
    

    I've also created some test cases. 0 fails, since there is another representation for 2^-1023.

    var tests = [1, -1, .123, -.123, 1.5, -1.5, 1e100, -1e100, 
                        1e-100, -1e-100, Infinity, -Infinity];
    
    tests.forEach(function(x)
    {
        var parts = getNumberParts(x),
            value = Math.pow(-1, parts.sign) *
                        Math.pow(2, parts.exponent) *
                        parts.mantissa;
    
        console.log("Testing: " + x + " " + value);
        console.assert(x === value);
    });
    
    console.log("Tests passed");
    

提交回复
热议问题