Skip to content
Advertisement

Offset is outside the bounds of the DataView, the debugger shows it is inside the bounds

I get the error Offset is outside the bounds of the DataView for the following code

JavaScript

Here is the debug view in Chrome

enter image description here

You can see that i is 47999 and the buffer size of my DataView is 48000. What am I missing here?

Advertisement

Answer

This is because an Int16Array has a 2 bytes per element. So its .length will be twice smaller than its buffer’s actual size, use its .byteLength instead to create a new ArrayBuffer of the same size.
Also, setting an int16 will actually set two bytes at a time.

So at some point, your loop will try to set a byte that doesn’t exist, and it will throw that error.

But that’s not all with your code. Since forEach()‘s iteration value i is based on the .length value of the TypedArray, you also need to multiply it by the TypedArray’s bytes per element to set a correct offset in DataView.setInt16.

JavaScript

Now, I’m not sure what you were wanting to do with this snippet, but to make a copy of your TypedArray, then you’d have to check for the endianness of the computer and then use the third parameter of DataView.setInt16( byteOffset, value, littleEndian ), but you could also simply do:

JavaScript

If you wanted to swap from little endian to big endian, then you could also make it way faster than using a DataView by first checking the computer’s endianness and swapping the values using .map if necessary.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement