سؤال

Thought I understood how Float32Array works, but it looks like I'm not quite there. In the simplest example possible:

buffer = new ArrayBuffer(128);
dataView = new DataView(buffer);
floatArray = new Float32Array(buffer);

dataView.setFloat32(8, 7);
console.log(floatArray[2]); //prints gibberesh

The way I understood it, the data view should set a float starting at the 8th byte to be 7, so the third float in the float array I would expect to be 7.

What am I missing here?

Thanks

هل كانت مفيدة؟

المحلول

This makes it work, the last parameter being littleEndian

dataView.setFloat32(8, 7, true);

This might be better, although I can't say for sure. Presumably Float32Array always uses the system's littleEndian, while DataView can use either.

var littleEndian = (function() {
  var buffer = new ArrayBuffer(2);
  new DataView(buffer).setInt16(0, 256, true);
  return new Int16Array(buffer)[0] === 256;
})();

dataView.setFloat32(8, 7, littleEndian);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top