在Javascript中解压缩半精度浮点数 [英] Decompressing Half Precision Floats in Javascript

查看:122
本文介绍了在Javascript中解压缩半精度浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用包含大量16位浮点数的javascript读取二进制文件。相当肯定它是IEEE标准,小端。将两个字节读入int非常简单,但是从那里我没有太大成功将其扩展为完整的浮点数。任何线索?

I'm trying to read a binary file with javascript that contains a lot of 16-bit floating point numbers. Fairly certain it's IEEE standard, little endian. It's pretty straightforward to read the two bytes into an int, but from there I'm not having much success expanding that out into a full floating point number. Any clues?

推荐答案

我最终根据维基百科页面上的信息实现了自己的解析器。它可能不是那里最快的,但我并不太关心。这是对那些好奇的人:

I ended up implementing my own parser based on the information on the Wikipedia page. It's probably not the fastest out there, but I'm not too concerned about that. Here it is for those that are curious:

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
}

这篇关于在Javascript中解压缩半精度浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆