Search code examples
javascriptfixed-pointeddystone

How to parse a hex value that is represented by signed 8.8 fixed-point notation? (JavaScript)


I would like to parse a two-byte value that is "expressed in a signed 8.8 fixed-point notation". Let's assume that I have the two bytes in the hexadecimal format below.

let data = '1800';

The 0x1800 in hexadecimal 8.8 fixed point notation should be 24 when converted.

Another example: 0x8000 in hexadecimal signed 8.8 fixed point notation should be -128 when converted.

More details

I'm specifically attempting to parse the temperature from an Eddystone Telemetry frame, which is defined here: https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md#field-notes


Solution

  • You can create a prototype from a custom object. Like this:

    function FixedPoint(fraction){
      this.fraction = fraction;
    }
    
    FixedPoint.prototype.calculate = function(value){
      let intValue = parseInt(value, 16);
      let signed = (intValue & 0x8000) > 0 ? -1 : 1;
      return signed * intValue / Math.pow(2, this.fraction);
    }
    

    How to use it?

    let example = new FixedPoint(8);
    example.calculate('1840');
    

    returns 24.25

    More info about fixed point here