6

In typed array specification there is a constructor that allows to take an existing ArrayBuffer and treat is as another array type. It is interesting that offset parameter must be a multiple of the underlying type of the constructed array. What was the reason for this limitation?

For background - I am trying to encode a binary buffer to be sent over WebSocket. The buffer contains various variables of different size. Originally I wanted to use the following code:

var buffer = new ArrayBuffer(10);
new Uint32Array(buffer, 0, 1)[0] = 234;
new Int16Array(buffer, 4, 1)[0] = -23;
new Uint32Array(buffer, 6, 1)[0] = 6000;  // Exception is raised here, 
                                          // because 6 is not multiple of 4

To make this work I would need to rewrite last line as following:

var tempArray = new Uint32Array(1);         // Create 32-bit array
tempArray[0] = 6000;                        // Write 32-bit number
var u8Src = new Uint8Array(tempArray, 0);   // Create 8-bit view of the array
var u8Dest = new Uint8Array(buffer, 6, 4);  // Create 8-bit view of the buffer
u8Dest.set(u8Src);                          // Copy bytes one by one

This is too much code for such a simple operation.

Sergiy Belozorov
  • 5,856
  • 7
  • 40
  • 73
  • possible duplicate of [Strange limitation in ArrayBufferView constructor](http://stackoverflow.com/questions/7554462/strange-limitation-in-arraybufferview-constructor) or [Why is creating a Float32Array with an offset that isn't a multiple of the element size not allowed?](http://stackoverflow.com/questions/7372124/why-is-creating-a-float32array-with-an-offset-that-isnt-a-multiple-of-the-eleme) – Bergi Mar 23 '13 at 17:28
  • Thanks for finding a duplicate. I tried searching for it, but failed to find. I guess there are many ways to formulate this question. – Sergiy Belozorov Mar 24 '13 at 18:06
  • Try this: let arrayData = new Uint32Array(buffer.slice(data.byteOffset), 0, length); – Haryono Oct 02 '20 at 06:49

1 Answers1

8

Unaligned memory access doesn't work on all platforms:

Why is creating a Float32Array with an offset that isn't a multiple of the element size not allowed? http://en.wikipedia.org/wiki/Data_structure_alignment

Use DataView object to access non-aligned data:

https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays/DataView

Community
  • 1
  • 1