/** * IEEE 754 half-precision numbers. * * Copyright (c) 2019-2026 Qianqian Fang . BSD 3-clause license. */ const f32 = new Float32Array(1); const u32 = new Uint32Array(f32.buffer); export function halfToFloat(h: number): number { const s = h & 0x8000 ? -1 : 1; const e = (h >> 10) & 0x1f; const f = h & 0x3ff; if (e === 0) { return s * f * 5.960464477539063e-8; // 2^-24 } if (e === 31) { return f ? NaN : s * Infinity; } return s * (1 + f / 1024) * Math.pow(2, e - 15); } export function floatToHalf(x: number): number { f32[0] = x; const b = u32[0]; const s = (b >>> 16) & 0x8000; const e = (b >>> 23) & 0xff; let m = b & 0x7fffff; if (e === 255) { return s | 0x7c00 | (m ? 0x200 : 0); } let he = e - 127 + 15; if (he >= 31) { return s | 0x7c00; } if (he <= 0) { if (he < -10) { return s; } m |= 0x800000; const shift = 14 - he; let hm = m >> shift; const rest = m & ((1 << shift) - 1), half = 1 << (shift - 1); if (rest > half || (rest === half && (hm & 1))) { hm++; } return s | hm; } let hm = m >> 13; const rest = m & 0x1fff; if (rest > 0x1000 || (rest === 0x1000 && (hm & 1))) { hm++; if (hm === 0x400) { hm = 0; he++; if (he >= 31) { return s | 0x7c00; } } } return s | (he << 10) | hm; }