Search code examples
javascriptserializationfloating-pointmathieee-754

Read/Write bytes of float in JS


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 get a byte-by-byte IEEE 754 representation? And same question for writing of course.


Solution

  • Would this snippet help?

    var parser = new BinaryParser
      ,forty = parser.encodeFloat(40.0,2,8) 
      ,twenty = parser.encodeFloat(20.0,2,8);  
    console.log(parser.decodeFloat(forty,2,8).toFixed(1));   //=> 40.0
    console.log(parser.decodeFloat(twenty,2,8).toFixed(1));  //=> 20.0