在Javascript中解压缩半精度浮点数

Decompressing Half Precision Floats in Javascript

本文关键字:精度 浮点数 解压缩 Javascript      更新时间:2023-09-26

我试图读取包含大量16位浮点数的javascript二进制文件。很确定这是IEEE标准,小尾端。将这两个字节读入int型很简单,但是从那里扩展成一个完整的浮点数就不太成功了。有线索吗?

@Toji:非常感谢!这是一个针对V8等非高端引擎进行优化的版本

var pow = Math.pow;
function decodeFloat16 (binary) {"use strict";
    var exponent = (binary & 0x7C00) >> 10,
        fraction = binary & 0x03FF;
    return (binary >> 15 ? -1 : 1) * (
        exponent ?
        (
            exponent === 0x1F ?
            fraction ? NaN : Infinity :
            pow(2, exponent - 15) * (1 + fraction / 0x400)
        ) :
        6.103515625e-5 * (fraction / 0x400)
    );
};

和更完整的IEEE 754测试:

function test() {
    var samples = [
        0x3C00, // = 1
            0xC000, // = −2
            0x7BFF, // = 6.5504 × 10^4 (max half precision)
            0x0400, // = 2^−14 ≈ 6.10352 × 10^−5 (minimum positive normal)
            0x0001, // = 2^−24 ≈ 5.96046 × 10^−8 (minimum strictly positive subnormal)
            0x0000, // = 0
            0x8000, // = −0
            0x7C00, // = Infinity
            0xFC00, // = −Infinity
            0x3555, // ≈ 0.33325... ≈ 1/3
            0x7C01  // = NaN
        ],
        i = samples.length;
    while (i--) samples[i] = decodeFloat16(samples[i]);
    return samples.join("'n");
};

与Toji原始代码比较的性能测试结果:

  • Chrome 17: + 30%
  • Safari 5.1: - 10%(不要问我为什么)
  • Firefox 9: + 11%
  • IExplorer 9: + 22%
  • IExplorer 7: + 14%

我最终基于Wikipedia页面上的信息实现了自己的解析器。它可能不是最快的,但我不太担心。这是给那些好奇的人的:

function float16_to_float(h) {
    var s = (h & 0x8000) >> 15;
    var e = (h & 0x7C00) >> 10;
    var f = h & 0x03FF;
    if(e == 0) {
        return (s?-1:1) * Math.pow(2,-14) * (f/Math.pow(2, 10));
    } else if (e == 0x1F) {
        return f?NaN:((s?-1:1)*Infinity);
    }
    return (s?-1:1) * Math.pow(2, e-15) * (1+(f/Math.pow(2, 10)));
}
function test() {
    float16_to_float(parseInt('3C00', 16)); // 1
    float16_to_float(parseInt('C000', 16)); // -2
    float16_to_float(parseInt('7BFF', 16)); // 6.5504 × 10^4 (Maximum half precision)
    float16_to_float(parseInt('3555', 16)); // 0.33325... ≈ 1/3
    // Works with all the test cases on the wikipedia page
}

从jspack中获取灵感。以前也有人尝试过类似的东西

开始阅读这篇维基百科文章。为了实现,我将创建一个查找表。(或者两个,一个用于高字节,一个用于低字节)