【发布时间】:2017-06-05 16:44:20
【问题描述】:
我正在尝试从使用 Java 创建的二进制文件中读取 javascript 中的浮点数。
文件是在 Java 中使用 DataOutputStream 创建的:
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
dos.writeFloat(-222);
dos.writeFloat(222000);
dos.writeFloat(130.329f);
dos.flush();
dos.close();
该文件由 http 请求检索,内容如下:
var client = new XMLHttpRequest();
client.addEventListener("load", dataLoaded);
client.open("GET", "/ajax-requests.php?data=true", true);
client.responseType = "arraybuffer";
client.send();
数据加载函数:
function dataLoaded () {
console.log("Float32Array: " + new Float32Array(this.response));
}
输出:
Float32Array: 3.3994099446055737e-41,1.8766110561523948e-38,0.00020218738063704222
期待:
Float32Array: -222,222000,130.329
文件用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>";
}
似乎转换中的某个地方存在缺陷,但我不知道在哪里。
更新:
正如 Sean Van Gorder 所说,问题是字节顺序的不同。为了解决这个问题,我使用 DataView 读取 arrayBuffer(因为文件将在 java 和 javascript 中读取,这是最好的解决方案)
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));
输出:
dataView: -222
dataView: 222000
dataView: 130.32899475097656
【问题讨论】:
-
谷歌
what every computer scientist needs to know about floating point
标签: javascript java php file