Alfredo Gimenez
Alfredo Gimenez

Reputation: 2224

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. 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. 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?

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'. http://www.mathworks.com/help/matlab/ref/fwrite.html

Upvotes: 3

Views: 1924

Answers (1)

Ast Derek
Ast Derek

Reputation: 2729

Endianness of your data is important: Javascript Typed Arrays and 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.

Upvotes: 3

Related Questions