2015-07-04 89 views
2

我想將一個緩衝區寫入一個數組,然後使用Float64Array視圖訪問該數組。這似乎比它應該更加困難。我已經使用了mozilla文檔,但仍然存在問題....在DataView中存儲緩衝區,然後使用Float64Array解壓縮

我嘗試了以下多種變體。有誰知道爲什麼這不起作用?最後我應該能夠打印出第一條浮法這是4

//64 bit floating point numbers with 8 bytes each in hex 
//first float64 bytes : 4 = 0x4010000000000000 
//second float64 bytes : 5 = 0x4014000000000000 

//2 x 8 bytes in a buffer with each hex number 
var buff = new Buffer("40100000000000004014000000000000", "hex"); 
var ab = new ArrayBuffer(buff.length); 
var view = new DataView(ab); 

for (var i = 0; i < buff.length; ++i) { 
    view[i] = buff[i]; 
} 

console.log(new Float64Array(ab).length);//prints 2 
console.log(new Float64Array(ab)[0]);// SHOULD print '4' but prints 0 

回答

0

我最終意識到數據需要被正確的塊讀入'INTO'。在我提供的例子中,這意味着兩個8字節的讀取。每次讀取都需要在Float64Array中填充一個項目。驚訝這並不容易,我不能只用整個基礎緩衝區填充ArrayBuffer。

反正這是我結束了......

var buff = new Buffer("40100000000000004014000000000000", "hex"); 
var ab = new ArrayBuffer(buff.length); 
var view = new Float64Array(ab); 

var viewIndex = 0; 
for (var bufferIndex=0;bufferIndex<buff.length;bufferIndex=bufferIndex+8)   { 

    view[viewIndex] = buff.readDoubleLE(bufferIndex); 
    viewIndex++; 
} 
1

Probs由於endianness。使用節點Buffer API:

var buff = new Buffer("40100000000000004014000000000000", "hex"); 
buff.readDoubleLE(0) // 2.0553e-320 
buff.readDoubleBE(0) // 4 

如果我們反向的buff和從第8字節讀:

var buffRev = new Buffer("00000000000014400000000000001040", "hex") 
buff.readDoubleLE(8) // 4 
buff.readDoubleBE(8) // 2.0553e-320 

隨時糾正/如果你知道更多的擴展。

相關問題