How to convert a floating point number to its binary representation (IEEE 754) in Javascript?

前端 未结 2 829
说谎
说谎 2021-02-01 18:19

What\'s the easiest way to convert a floating point number to its binary representation in Javascript? (e.g. 1.0 -> 0x3F800000).

I have tried to do it manually, and this

2条回答
  •  孤城傲影
    2021-02-01 18:30

    new technologies are making this easy and probably also more forward-compatible. I love extending built in prototypes, not everyone does. So feel free to modify following code to classical procedural approach:

    (function() {
        function NumberToArrayBuffer() {
            // Create 1 entry long Float64 array
            return [new Float64Array([this]).buffer];
        }
        function NumberFromArrayBuffer(buffer) {
            // Off course, the buffer must be at least 8 bytes long, otherwise this is a parse error
            return new Float64Array(buffer, 0, 1)[0];
        }
        if(Number.prototype.toArrayBuffer)  {
            console.warn("Overriding existing Number.prototype.toArrayBuffer - this can mean framework conflict, new WEB API conflict or double inclusion.");
        }
        Number.prototype.toArrayBuffer = NumberToArrayBuffer;
        Number.prototype.fromArrayBuffer = NumberFromArrayBuffer;
        // Hide this methods from for-in loops
        Object.defineProperty(Number.prototype, "toArrayBuffer", {enumerable: false});
        Object.defineProperty(Number.prototype, "fromArrayBuffer", {enumerable: false});
    })();
    

    Test:

    (function() {
        function NumberToArrayBuffer() {
            // Create 1 entry long Float64 array
            return new Float64Array([this.valueOf()]).buffer;
        }
        function NumberFromArrayBuffer(buffer) {
            // Off course, the buffer must be ar least 8 bytes long, otherwise this is a parse error
            return new Float64Array(buffer, 0, 1)[0];
        }
        if(Number.prototype.toArrayBuffer)  {
            console.warn("Overriding existing Number.prototype.toArrayBuffer - this can mean framework conflict, new WEB API conflict or double inclusion.");
        }
        Number.prototype.toArrayBuffer = NumberToArrayBuffer;
        Number.fromArrayBuffer = NumberFromArrayBuffer;
        // Hide this methods from for-in loops
        Object.defineProperty(Number.prototype, "toArrayBuffer", {enumerable: false});
        Object.defineProperty(Number, "fromArrayBuffer", {enumerable: false});
    })();
    var test_numbers = [0.00000001, 666666666666, NaN, Infinity, -Infinity,0,-0];
    console.log("Conversion symethry test: ");
    test_numbers.forEach(
          function(num) {
                   console.log("         ", Number.fromArrayBuffer((num).toArrayBuffer()));
          }
    );
    
    console.log("Individual bytes of a Number: ",new Uint8Array((666).toArrayBuffer(),0,8));

提交回复
热议问题