Create typed array from part of a binary buffer Javascript

问题: I have a binary buffer, the first half contains data meant to be read as an int using the Uint32 view. The second half is meant to be read as a char using the Uint8 view....

问题:

I have a binary buffer, the first half contains data meant to be read as an int using the Uint32 view. The second half is meant to be read as a char using the Uint8 view.

However the problem is the length of the char data is never guaranteed to be divisible by 4.

So if the length of the int data is 7, and the length of the char data is 5 then when I go to make the arrays I get a response like this:

 var Unit8Array = new Uint8Array(buffer);
 var Unit32Array = new Uint32Array(buffer);
 console.log(Unit8Array.length) // 32; (It's 32 because 7*4 + 5 = 32)
 console.log(Uint32Array.length) // Error Array Buffer out of bounds

So as you can see I can't create the Uint32 array because the entire buffer isn't divisible by the size of an Int. However I only need the first half of the data in that Uint32 array.

Is there any way to fix this problem without creating a new buffer? For performance reasons I was hoping to read the same data in memory just using different views or separating the buffer (meaning multiple downloads, as I get this buffer from an xhr request).

I tried to do this:

 var uint8Array= new Uint8Array(buffer);
 var padding = uint8Array.length + (4 - uint8Array%4);
 var uint32Array = new Uint32Array(buffer- padding);

But that just makes uint32Array be undefined.


回答1:

If you want to initialize a Uint32Array from the largest aligned segment of a given array buffer, you can do this:

var byteLength = buffer.byteLength;
var alignment = Uint32Array.BYTES_PER_ELEMENT;
var alignedLength = byteLength - (byteLength % alignment);
var alignedBuffer = buffer.slice(0, alignedLength);
var uint32Array = new Uint32Array(alignedBuffer);
  • 发表于 2018-07-14 02:00
  • 阅读 ( 297 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除