Skip to content

Commit 18d2585

Browse files
authored
Merge pull request #18 from usnistgov/float16
add float16 support
2 parents b1c4186 + aa4a103 commit 18d2585

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

esm/core.js

+31
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ class Struct {
7878
"L": "getUint32",
7979
"q": "getInt64",
8080
"Q": "getUint64",
81+
"e": "getFloat16",
8182
"f": "getFloat32",
8283
"d": "getFloat64"
8384
}
@@ -93,6 +94,7 @@ class Struct {
9394
"L": 4,
9495
"q": 8,
9596
"Q": 8,
97+
"e": 2,
9698
"f": 4,
9799
"d": 8
98100
}
@@ -165,7 +167,36 @@ var MIN_INT64 = -1n << 63n;
165167
var MAX_UINT64 = 1n << 64n;
166168
var MIN_UINT64 = 0n;
167169

170+
171+
function decodeFloat16(low, high) {
172+
// decode IEEE 754 half-precision (2 bytes)
173+
let sign = (high & 0b10000000) >> 7;
174+
let exponent = (high & 0b01111100) >> 2;
175+
let fraction = ((high & 0b00000011) << 8) + low;
176+
177+
let magnitude;
178+
if (exponent == 0b11111) {
179+
magnitude = (fraction == 0) ? Infinity : NaN;
180+
}
181+
else if (exponent == 0) {
182+
magnitude = 2**-14 * (fraction / 1024);
183+
}
184+
else {
185+
magnitude = 2**(exponent - 15) * (1 + (fraction/1024));
186+
}
187+
188+
return (sign) ? -magnitude : magnitude;
189+
}
190+
168191
export class DataView64 extends DataView {
192+
getFloat16(byteOffset, littlEndian) {
193+
// little-endian by default
194+
let bytes = [this.getUint8(byteOffset), this.getUint8(byteOffset + 1)]
195+
if (!littlEndian) bytes.reverse();
196+
let [low, high] = bytes;
197+
return decodeFloat16(low, high);
198+
}
199+
169200
getUint64(byteOffset, littleEndian) {
170201
// split 64-bit number into two 32-bit (4-byte) parts
171202
const left = BigInt(this.getUint32(byteOffset, littleEndian));

0 commit comments

Comments
 (0)