Creating Typed Arrays from ArrayBuffer
You'll learn how to create typed array views that "look into" specific portions of an ArrayBuffer, giving you fine control over which bytes you're working with.
The Core Idea
An ArrayBuffer is raw binary memory—just bytes with no interpretation. A typed array is a view that interprets those bytes as numbers of a specific type. When you create a typed array from an existing ArrayBuffer, you can specify exactly which portion of that buffer to view by providing a byte offset (where to start) and a length (how many elements to include).
Think of it like looking through a window into a long hallway (the ArrayBuffer). You can position your window (byte offset) anywhere along the hallway and decide how wide it should be (length).
Creating Views with Offset and Length
// Start with a 16-byte buffer
const buffer = new ArrayBuffer(16);
// View the first 4 bytes as a single 32-bit integer
const view1 = new Int32Array(buffer, 0, 1);
// View bytes 4-11 as two 32-bit integers
const view2 = new Int32Array(buffer, 4, 2);
// View bytes 12-15 as four 8-bit unsigned integers
const view3 = new Uint8Array(buffer, 12, 4);
view1[0] = 100;
view2[0] = 200;
view2[1] = 300;
view3[0] = 10;
console.log(view1[0]); // 100
console.log(view2); // Int32Array [200, 300]
The syntax is: new TypedArray(buffer, byteOffset, length). The byteOffset must align with the type's byte size (e.g., Int32Array needs offsets divisible by 4).
Key Takeaway: You can create multiple typed array views over different portions of the same ArrayBuffer, each with its own byte offset and element length, allowing precise control over binary data interpretation.