Typed Arrays (accessing raw binary data)

JS
S
JavaScript

JavaScript typed arrays are array-like objects and provide a mechanism for accessing raw binary data. This snippet provides a trivial basic introduction. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

1/* Web APIs using typed arrays
2  FileReader.prototype.readAsArrayBuffer()  // Blob or File.
3  XMLHttpRequest.prototype.send() // ArrayBuffer
4  ImageData.data // 0-255 integers
5  View Types
6  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_objects
7*/
8
9
10// Create a chunk of memory whose bytes are all pre-initialized to 0, 16 bytes long
11const buffer = new ArrayBuffer(16);
12
13// Create a View thattreats the data in the buffer as an array of 32-bit signed integers (4 digits, 4*8=32)
14const int32View = new Int32Array(buffer);
15// console.log(int32View.length)
16
17// Read buffer (through view)
18int32View[0] = 64; // set int 64 on position 0
19for (var i = 0; i < int32View.length; i++) {
20  // console.log(int32View[i])
21}
22
23// Create another View that treats the data in the buffer as an array of 16-bit signed integers (8 digits)
24const int16View = new Int16Array(buffer);
25// console.log(int16View.length)
26int16View[4]= 64;
27// console.log(int16View)
28
29// Same buffer, different views, same data
30int32View[3] = 9;
31// console.log(int16View) // int16View[6] // 9
32
33// Convert to normal array
34const normalArray = Array.from(int32View);
35console.log(normalArray, normalArray.constructor)
36console.log(int32View, int32View.constructor)

Created on 2/20/2018