从二进制文件中读取浮点值(在后效脚本中)

时间:2017-02-10 13:45:34

标签: javascript binary floating-point extendscript after-effects

我有一个包含使用c程序记录的数据的二进制文件。 存储在文件中的数据是浮点值。 现在我需要从后效应脚本中的二进制文件中检索浮点数。 这是我的代码:

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);
     ???
}

问题是如何将缓冲区转换为浮点数。 非常感谢提前。

输入文件是这样的:

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任何sepration字符(,)

每个浮点数使用4个字节。

1 个答案:

答案 0 :(得分:0)

试试这个。它假定输入是由IEEE 754 floating-point standard编写的。我使用了this answer中的解析函数。示例输入文件为here。它由4个值(7.26,-3.32,-5.18,7.66)组成,没有分隔符,因此它的大小为4 * 4 = 16个字节。

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;
}