Read/Write bytes of float in JS

前端 未结 6 1778
野趣味
野趣味 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:27

    Koolinc's snippet is good if you need a solution that powerful, but if you need it for limited use you are better off writing your own code. I wrote the following function for converting a string hex representation of bytes to a float:

    function decodeFloat(data) {
        var binary = parseInt(data, 16).toString(2);
        if (binary.length < 32) 
            binary = ('00000000000000000000000000000000'+binary).substr(binary.length);
        var sign = (binary.charAt(0) == '1')?-1:1;
        var exponent = parseInt(binary.substr(1, 8), 2) - 127;
        var significandBase = binary.substr(9);
        var significandBin = '1'+significandBase;
        var i = 0;
        var val = 1;
        var significand = 0;
    
        if (exponent == -127) {
            if (significandBase.indexOf('1') == -1)
                return 0;
            else {
                exponent = -126;
                significandBin = '0'+significandBase;
            }
        }
    
        while (i < significandBin.length) {
            significand += val * parseInt(significandBin.charAt(i));
            val = val / 2;
            i++;
        }
    
        return sign * significand * Math.pow(2, exponent);
    }
    

    There are detailed explanations of algorithms used to convert in both directions for all formats of floating points on wikipedia, and it is easy to use those to write your own code. Converting from a number to bytes should be more difficult because you need to normalize the number first.

提交回复
热议问题