0

I have to unpack a binary file where some values are half-precision floats (i.e. float16).

I read it from the binary stream by using the specification API dataView.getUint16(0).

How can I convert a number in uint16 formatback tofloat16` format using JavaScript?

jwpfox
  • 5,124
  • 11
  • 45
  • 42
  • read [this](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) - see if you can figure it out – Jaromanda X Nov 23 '16 at 23:37
  • by the way, javascript has no "float16", so you'll never convert it to an actual float16 - you can convert it to a `Number`, or event a float32 or float64 (Number) - if what you want to do is read "float16", manipulate the value and store/write/send "float16" - you'll need to first convert the binary data that you have in the uint16 to a Number, manipulate it, then convert that back to a uint16 – Jaromanda X Nov 23 '16 at 23:49

1 Answers1

1

All number variables in Javascript are treated as 64 bit floats (doubles).

Once you have read it from a DataView into a variable, it will be in that form.

The set* methods on the DataView object allow you to set bytes in an ArrayBuffer using various packed forms:

dv.setUint16(0, 12);
dv.getUint16(0); // >>> 12

But you have to be careful about clamping it yourself:

dv.setUint16(0, -12);
dv.getUint16(0); // >>> 65524

For signed int16:

dv.setInt16(0, -12);
dv.getInt16(0); // >>> -12