2017-06-05 146 views
0

我想從使用Java創建的二進制文件讀取JavaScript中的浮動。從二進制文件讀取浮動javascript

該文件使用DataOutputStream在Java中創建:

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

該文件是由http請求retreived和讀取這樣的:

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

dataLoaded功能:

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

輸出:

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

似乎冥冥之中有在轉換中的缺陷,但我想不通的地方。

UPDATE:

的問題是,就像肖恩·範·Gorder指出,在字節順序不同。要解決這一點,我用數據視圖讀取arrayBuffer(因爲文件都將在Java和JavaScript中這種閱讀是最好的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)); 

輸出:

dataView: -222 
dataView: 222000 
dataView: 130.32899475097656 
+0

Google' – RiggsFolly

回答

1

你有一個字節順序不匹配。 DataOutputStream以big-endian寫入,但Float32Array通常以little-endian讀取(取決於硬件)。您必須更改the Java sidethe Javascript side以匹配。 「每個計算機科學家需要了解的浮點數」#: