将位数组转换为字节并浮点数

时间:2019-04-29 09:43:59

标签: javascript bitwise-operators arraybuffer

我正在尝试从数组(仅包含位)中读取浮点数(每个浮点32位) 当我尝试使用ArrayBuffer和DataView进行操作时,最后得到了奇怪的值。 我期望有2个浮点数,但我看到所有数字都是0。

我在这里想念什么? 我希望按顺序从4个byes中分别获取2个floats(firsNum,secNum)

// 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)

1 个答案:

答案 0 :(得分:2)

除了这些注释: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(大字节序),此刻显示“ 4240”(小)字节序,这可能仍然是错误的)。翻转位顺序通常会产生怪异的数字,但是第二个星座会得到-35.5。