JavaScript: ArrayBuffer and TypedArray

JavaScript typed arrays split the implementation into buffers and views. A buffer (implemented by the ArrayBuffer object) is an object representing a chunk of data; it has no format to speak of and offers no mechanism for accessing its contents. In order to access the memory contained in a buffer, you need to use a view. A view provides a context — that is, a data type, starting offset, and the number of elements — that turns the data into a typed array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
Typed arrays in an ArrayBuffer
TypeValue RangeSize in bytesDescriptionWeb IDL typeEquivalent C type
Int8Array-128 to 12718-bit two’s complement signed integerbyteint8_t
Uint8Array0 to 25518-bit unsigned integeroctetuint8_t
Uint8ClampedArray0 to 25518-bit unsigned integer (clamped)octetuint8_t
Int16Array-32768 to 32767216-bit two’s complement signed integershortint16_t
Uint16Array0 to 65535216-bit unsigned integerunsigned shortuint16_t
Int32Array-2147483648 to 2147483647432-bit two’s complement signed integerlongint32_t
Uint32Array0 to 4294967295432-bit unsigned integerunsigned longuint32_t
Float32Array1.2×10-38 to 3.4×1038432-bit IEEE floating point number (7 significant digits e.g., 1.123456)unrestricted floatfloat
Float64Array5.0×10-324 to 1.8×10308864-bit IEEE floating point number (16 significant digits e.g., 1.123...15)unrestricted doubledouble
BigInt64Array-263 to 263-1864-bit two’s complement signed integerbigintint64_t (signed long long)
BigUint64Array0 to 264-1864-bit unsigned integerbigintuint64_t (unsigned long long)

Example

> u8view
Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

> u32view
Uint32Array [ 0, 0, 0, 0 ]

> u8view[0] = 255
255
> u32view[0]
255

// 257 is greater than 255, will become 1
// 1[00000001] = 257 => 1
// 1[00000000] = 256 => 0
> u8view[1] = 257
257

> u8view[1]
1

// 32 byte view, the first element is 256 (u8view[1]) + 255(u8view[0]) = 511
> u32view[0]
511

> u8view[3] = 1
1

// 32 byte view, the first element is (2^24 + 1) + (2^16 * 0) + (2^8 + 1) + 255
//                                    16777216   + 0          + 256       + 255 = 16777727
> u32view[0]
16777727

> u8view
Uint8Array [ 255, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

> u32view
Uint32Array [ 16777727, 0, 0, 0 ]

Leave a Comment

Your email address will not be published. Required fields are marked *