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.

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

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧