Typed arrays and ArrayBuffer — fixed-type views over raw bytes¶
Level: 201 · for anyone who has to handle raw bytes
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: A typed array converts each value to its element type, so new Uint8Array([256, -1, 3.7]) holds 0, 255, 3; it never grows, and views share one ArrayBuffer: a Uint32Array writes it little-endian on x86 and ARM, while DataView reads big-endian by default.
Keywords: ArrayBuffer, TypedArray, Uint8Array, Uint8ClampedArray, DataView
What the finished page will answer¶
- What does each typed array do with a value it cannot hold: 256, -1 and 3.7 in a
Uint8Array, aUint8ClampedArrayand anInt8Array, and 0.1 in aFloat32Array? - What happens when you assign past the end of a typed array, and why is there no
push? - When a
Uint32Arrayand aUint8Arrayshare oneArrayBuffer, in what byte order do they see a number, and what doesDataViewread with and withoutlittleEndian? - Why does
new Uint8Array([10, 9, 1]).sort()sort numerically when a plain array does not? - Which methods share memory (
subarray) and which copy (slice), and what doesJSON.stringifymake of a typed array?
Examples it will need¶
-
typed_arrays_conversion_js.js— the same values stored inUint8Array,Uint8ClampedArray,Int8Array,Float32ArrayandFloat64Array, one line per type -
typed_arrays_views_js.js— oneArrayBufferseen throughUint8Array,Uint32ArrayandDataViewin both byte orders, thensubarraysharing memory whereslicecopies
See also¶
Buffer— theBufferclass, aUint8Arraysubclass with more methods- Strings and bytes —
TextEncoderreturns aUint8Arrayof UTF-8 SharedArrayBufferandAtomics— a buffer that two threads can see at once- Bitwise operators — the 32-bit conversion that
Int32Arrayalso applies on store sort()compares strings — why a plain array sorts[10, 9, 1]as strings- Encodings: The bytes do not say which end ↗ — bytes never record which end is the big one
- C: Byte order on the wire ↗ — network byte order, the big-endian that
DataViewuses by default - Encodings: Arithmetic has its own width ↗ — where a value wraps when it is stored back into a byte