douji9518 2017-06-05 16:44
浏览 95
已采纳

从二进制文件javascript中读取浮点数

I'm trying to read floats in javascript from a binary file that is created using Java.

The file is created in Java using DataOutputStream:

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
dos.writeFloat(-222);
dos.writeFloat(222000);
dos.writeFloat(130.329f);
dos.flush();
dos.close();

The file is retreived by http request and read like this:

var client = new XMLHttpRequest();
client.addEventListener("load", dataLoaded);
client.open("GET", "/ajax-requests.php?data=true", true);
client.responseType = "arraybuffer";
client.send();

dataLoaded function:

function dataLoaded () {
    console.log("Float32Array: " + new Float32Array(this.respnse));
}

Output:

Float32Array: 3.3994099446055737e-41,1.8766110561523948e-38,0.00020218738063704222

Expecting:

Float32Array: -222,222000,130.329

The file is sent with php:

if(isset($_GET['data'])) {
  $file_path = "data/filename.ext";

  if (file_exists($file_path)) {
    if(false !== ($handler = fopen($file_path, 'r'))) {
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . filesize($file_path));

        readfile($file_path);
    }
    exit;
  }
  echo "<h1>Content error</h1><p>The file does not exist!</p>";
}

It seems that somewhere there is a flaw in the conversion but I can't figure out where.

UPDATE:

The problem was just as Sean Van Gorder stated, a difference in endianness. To work around this I used DataView to read the arrayBuffer (since the file will be read both in java and in javascript this was the best sulotion)

var dataView = new DataView(arrayBuffer);
console.log("dataView: " + dataView.getFloat32(0, false));
console.log("dataView: " + dataView.getFloat32(4, false));
console.log("dataView: " + dataView.getFloat32(8, false));

Output:

dataView: -222
dataView: 222000
dataView: 130.32899475097656
  • 写回答

1条回答 默认 最新

  • dongxiejie9387 2017-06-05 17:58
    关注

    You've got a byte order mismatch. DataOutputStream writes in big-endian, but Float32Array usually reads in little-endian (depending on hardware). You'll have to change the Java side or the Javascript side to match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂