Read/Write bytes of float in JS

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

    You can do it with typed arrays:

    var buffer = new ArrayBuffer(4);
    var intView = new Int32Array(buffer);
    var floatView = new Float32Array(buffer);
    
    floatView[0] = Math.PI
    console.log(intView[0].toString(2)); //bits of the 32 bit float
    

    Or another way:

    var view = new DataView(new ArrayBuffer(4));
    view.setFloat32(0, Math.PI);
    console.log(view.getInt32(0).toString(2)); //bits of the 32 bit float
    

    Not sure what browser support is like though

提交回复
热议问题