[英]Store buffer in DataView then extract with Float64Array not working
我想將緩沖區寫入數組,然后使用 Float64Array 視圖訪問該數組。 這似乎比它應該的要困難得多。 我已經使用了 mozilla 文檔,但仍然有問題....
我已經嘗試了以下的多種變體。 有誰知道為什么這不起作用? 最后,我應該能夠打印出第一個浮點數 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
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
如果您了解更多,請隨時更正/擴展。
我最終意識到確實需要將數據以正確的塊讀取到視圖中。 在我提供的示例中,這意味着兩次讀取 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++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.