Javascript: How To Separate A U8intarray?
I have a U8IntArray with 20 bytes and I want to separate it into two parts (first 8 bytes and byte 9 to 20): var arr = new Uint8Array( 20 ); var part1 = arr.slice( 0, 8 ); var part
Solution 1:
The problem is that Typed Arrays were initially defined by the Typed Array Specification, which did not define any slice
method in the TypedArray
interface.
Now Typed Arrays are part of ECMAScript 6, but Internet Exporer don't support it completely.
So it will be safer to use only methods defined in the old spec. In this case, TypedArray.prototype.subarray
should work since IE10.
var arr = newUint8Array( 20 );
var part1 = arr.subarray( 0, 8 );
var part2 = arr.subarray( 8 );
console.info( part1, part2 );
Another alternative is using slice
on the buffer instead of directly on the array, supported since IE11.
var arr = newUint8Array( 20 );
var part1 = newUint8Array( arr.buffer.slice( 0, 8 ) );
var part2 = newUint8Array( arr.buffer.slice( 8 ) );
console.info( part1, part2 );
Solution 2:
You can create a new Uint8Array
from the original buffer source, then specify the second and the third arguments to retrieve the expected bytes.
var arr = newUint8Array( 20 );
var part1 = newUint8Array(arr.buffer, 0, 8);
var part2 = newUint8Array(arr.buffer, 8);
Just note that this method doesn't slice the original ArrayBuffer
.
Post a Comment for "Javascript: How To Separate A U8intarray?"