Search code examples
javascriptparsingraw-data

Parsing to 16-bit value in second complement form


The datasheet put me 2 byte for a data, which is defined as :

"These two byte is a 16-bit value in 2's complement form, whose range is from 0xF800 (-4096) to 0x07FF (4095)"

I don't really understand how to parse this data in javascript.


Solution

  • All current mainstream browsers support the DataView class.

    Given your Uint8Array containing e.g. [0xf8, 0x00]:

    var a = new Uint8Array([0xf8, 0x00])
    

    you can treat this as array of Int16 values instead:

    var view = new DataView(a.buffer)
    var val = view.getInt16(0, false);   // false for big-endian
    > -2048
    

    If the data in your array is the other way around (little-endian) supply true for the second parameter to .getInt16().