Read/Write bytes of float in JS

前端 未结 6 1789
野趣味
野趣味 2020-11-28 09:46

Is there any way I can read bytes of a float value in JS? What I need is to write a raw FLOAT or DOUBLE value into some binary format I need to make, so is there any way to

6条回答
  •  天命终不由人
    2020-11-28 10:25

    I've created an expansion of Milos' solution that should be a bit faster, assuming TypedArrays are not an option of course (in my case I'm working with an environment where they're not available):

    function Bytes2Float32(bytes) {
        var sign = (bytes & 0x80000000) ? -1 : 1;
        var exponent = ((bytes >> 23) & 0xFF) - 127;
        var significand = (bytes & ~(-1 << 23));
    
        if (exponent == 128) 
            return sign * ((significand) ? Number.NaN : Number.POSITIVE_INFINITY);
    
        if (exponent == -127) {
            if (significand == 0) return sign * 0.0;
            exponent = -126;
            significand /= (1 << 22);
        } else significand = (significand | (1 << 23)) / (1 << 23);
    
        return sign * significand * Math.pow(2, exponent);
    }
    

    Given an integer containing 4 bytes holding an IEEE-754 32-bit single precision float, this will produce the (roughly) correct Javascript number value without using any loops.

提交回复
热议问题