Is there any way to see a number in it's 64 bit float IEEE754 representation

拟墨画扇 提交于 2019-12-01 17:26:21

You can use typed arrays to examine the raw bytes of a number. Create a Float64Array with one element, and then create a Uint8Array with the same buffer. You can then set the first element of the float array to your number, and examine the bytes via the Uint8Array. You'll have to do some shifting and combining for the various pieces of the number of course, but it's not hard.

There are no built-in facilities to do things like extract the exponent.

Based on @Pointy's suggestion I've implemented the following function to get a number in it's 64 bit float IEEE754 representation:

function to64bitFloat(number) {
    var f = new Float64Array(1);
    f[0] = number;
    var view = new Uint8Array(f.buffer);
    var i, result = "";
    for (i = view.length - 1; i >= 0; i--) {
        var bits = view[i].toString(2);
        if (bits.length < 8) {
            bits = new Array(8 - bits.length).fill('0').join("") + bits;
        }
        result += bits;
    }
    return result;
}

console.log(to64bitFloat(12)); // 0100000000101000000000000000000000000000000000000000000000000000
console.log(to64bitFloat(-12)); // 1100000000101000000000000000000000000000000000000000000000000000
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!