简体   繁体   English

如何使用XMLHttpRequest正确读取二进制浮点数据?

[英]How to correctly read binary floating-point data using XMLHttpRequest?

I'm trying to read a binary file of floating-point values into an array in JavaScript. 我试图在JavaScript中将浮点值的二进制文件读入数组。 Currently I'm doing so by: 目前我通过以下方式这样做:

var mRequest = new XMLHttpRequest();
mRequest.open('GET', 'res/binary_float_data.bin');
mRequest.responseType = 'arraybuffer';

mRequest.onreadystatechange = function () {
    if (mRequest.readyState === 4) {

        // Get bytes
        var buffer = mRequest.response;
        var dataview = new DataView(buffer);

        // Create buffer (4 bytes / float)
        var mFloatArray = new Float32Array(buffer.byteLength / 4);

        // Copy floats
        for (var i = 0; i < mFloatArray.length; i++) 
        {
            mFloatArray[i] = dataview.getFloat32(i * 4); // At every 4th byte
        }

        console.log("Loaded "+mFloatArray.length+" floats");

        // Do something with mFloatArray
    }
};

mRequest.send();

However, when I look at the minimum, maximum, and average values of the resulting array (mFloatArray), they are not correct. 但是,当我查看结果数组(mFloatArray)的最小值,最大值和平均值时,它们是不正确的。 They should be: 他们应该是:

min: -0.0094
max: 0.0081
avg: 1.3196e-04

Instead I am getting: 相反,我得到:

min: -3.3985008792505584e+38
max: 0
avg: NaN

I am certain the binary file is correct, am I correctly parsing the XMLHttpRequest? 我确定二进制文件是正确的,我正确解析XMLHttpRequest吗?

EDIT: Adding a small part of the binary file, in hex view: 编辑:在十六进制视图中添加二进制文件的一小部分:

0002980: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0002990: 0000 0000 0000 0000 0000 0000 55df 11bc  ............U...
00029a0: afc5 13bc c0b2 15bc 4205 17bc a094 17bc  ........B.......
00029b0: e3d4 17bc cb41 18bc f2e6 18bc 464d 19bc  .....A......FM..
00029c0: bb94 18bc f6ca 16bc 29a5 14bc 0000 0000  ........).......
00029d0: 0000 0000 0000 0000 0000 0000 0000 0000  ................

EDIT 2: I made the binary file using matlab and the "fwrite" command, with precision 'float32'. 编辑2:我使用matlab和“fwrite”命令制作二进制文件,精度为“float32”。 http://www.mathworks.com/help/matlab/ref/fwrite.html http://www.mathworks.com/help/matlab/ref/fwrite.html

Endianness of your data is important: Javascript Typed Arrays and Endianness 数据的字节顺序非常重要: Javascript Typed Arrays和Endianness

You'd need to detect endianness and extract the number byte per byte, or create two different versions of the file, detect endianness and retrieve the correct one for the current browser. 您需要检测字节顺序并提取每个字节的数字字节,或者创建文件的两个不同版本,检测字节顺序并为当前浏览器检索正确的字节顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM