我试图从一个数组(只包含位)读取浮点数(每个浮点数32位)当我尝试使用ArrayBuffer和DataView时,我最后得到了奇怪的值。我期待有两个浮点数,但我看到所有数字都是0。
我在这里错过了什么?我希望2个浮点数(firsNum,secNum)分别来自4个byes
// Simple array contain 8 bytes
var myBitsArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0];
// Array buffer with size of 8 bytes
const buffer = new ArrayBuffer(8);
// Loop all the data to the array buffer add 8 bits at each time
for (var i = 0; i < myBitsArr.length / 8; i++) {
var byteCounter = i * 8;
var b_0 = myBitsArr[byteCounter + 0] << 0;
var b_1 = myBitsArr[byteCounter + 1] << 1;
var b_2 = myBitsArr[byteCounter + 2] << 2;
var b_3 = myBitsArr[byteCounter + 3] << 3;
var b_4 = myBitsArr[byteCounter + 4] << 4;
var b_5 = myBitsArr[byteCounter + 5] << 5;
var b_6 = myBitsArr[byteCounter + 6] << 6;
var b_7 = myBitsArr[byteCounter + 7] << 7;
buffer[i] = (b_0 + b_1 + b_2 + b_3 + b_4 + b_5 + b_6 + b_7);
}
console.log(buffer)
// View the floating numbers
var viewNumbers = new DataView(buffer);
var firsNum = viewNumbers.getFloat32(0); // get 0 back and not float number
var secNum = viewNumbers.getFloat32(1); // get 0 back and not float number
console.log(firsNum, secNum)
除了这些评论:ArrayBuffer
不是一个数组,这就是为什么buffer[i]
没有做任何有用的事情。你需要一个typedarray,很可能是Uint8Array
,下面叫做uint8
:
// Simple array contain 8 bytes
var myBitsArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0];
// Array buffer with size of 8 bytes
const buffer = new ArrayBuffer(8);
const uint8 = new Uint8Array(buffer);
// Loop all the data to the array buffer add 8 bits at each time
for (var i = 0; i < myBitsArr.length / 8; i++) {
var byteCounter = i * 8;
var b_0 = myBitsArr[byteCounter + 0] << 0;
var b_1 = myBitsArr[byteCounter + 1] << 1;
var b_2 = myBitsArr[byteCounter + 2] << 2;
var b_3 = myBitsArr[byteCounter + 3] << 3;
var b_4 = myBitsArr[byteCounter + 4] << 4;
var b_5 = myBitsArr[byteCounter + 5] << 5;
var b_6 = myBitsArr[byteCounter + 6] << 6;
var b_7 = myBitsArr[byteCounter + 7] << 7;
uint8[i] = (b_0 + b_1 + b_2 + b_3 + b_4 + b_5 + b_6 + b_7);
}
console.log(buffer)
// View the floating numbers
var viewNumbers = new DataView(buffer);
var firsNum = viewNumbers.getFloat32(0,true); // get 0 back and not float number
var secNum = viewNumbers.getFloat32(4,true); // get 0 back and not float number
console.log(firsNum, secNum);
然后它做了一些事情,显示“4.600743118071239e-41 4.027191656623092e-41”没有true
-s(大端)和“4 240”此刻(小端,仍然可能是错误的)。通过翻转位顺序,它通常产生奇怪的数字,但是第二个星座得到-35.5。