-1

I have a binary file containing data recorded using a c program. the data stored in files are float values. Now I need to retrieve the float numbers from binary file in after effects script. This is my code:

var myFile = File.openDialog('select file');
myFile.open("r");
myFile.encoding = "binary";
for(x=0;x<myFile.length;x += 4){
     myFile.seek(x,0);
     buffer = myFile.read(4);
     ???
}

the question is how to convert the buffer to a float number. Many Thanks in advance.

the input file is somthing like this :

7.26,-3.32,-5.18 7.66,3.65,-5.37 8.11,-4.17,5.11 8.40,-5.17,4.80

whitout any sepration character (,)

Each floating-point number uses 4 byte.

1 Answers1

0

Try this. It assumes the input was written by IEEE 754 floating-point standard. I used the parsing function from this answer. Sample input file is here. It consists of 4 values(7.26, -3.32, -5.18, 7.66) without seperator, thereby its size is 4 * 4 = 16 bytes.

var myFile = File.openDialog('select file');
myFile.open("r");
myFile.encoding = "binary";

var buffers = [];
for(var x=0; x<myFile.length; x += 4) {
    myFile.seek(x, 0);
    var buffer = "0x";
    for(var y=0; y<4; y++) {
        var hex = myFile.readch().charCodeAt(0).toString(16);
        if(hex.length === 1) {
            hex = "0" + hex;
        }
        buffer += hex;
    }
    buffers.push(parseFloat2(buffer));

}
alert(buffers);


function parseFloat2(str) {
    // from https://stackoverflow.com/a/14090278/6153990
    var float2 = 0;
    var sign, order, mantiss, exp, int2 = 0, multi = 1;
    if (/^0x/.exec(str)) {
        int2 = parseInt(str,16);
    } else {
        for (var i = str.length -1; i >=0; i -= 1) {
            if (str.charCodeAt(i)>255) {
                alert('Wrong string parametr'); 
                return false;
            }
            int2 += str.charCodeAt(i) * multi;
            multi *= 256;
        }
    }
    sign = (int2>>>31)?-1:1;
    exp = (int2 >>> 23 & 0xff) - 127;
    mantiss = ((int2 & 0x7fffff) + 0x800000).toString(2);
    for (i=0; i<mantiss.length; i+=1){
        float2 += parseInt(mantiss[i])? Math.pow(2,exp):0;
        exp--;
    }
    return float2*sign;
}
Community
  • 1
  • 1
Sangbok Lee
  • 2,132
  • 3
  • 15
  • 33