JS: DataView
ai answer
JavaScript DataView Tutorial
DataView is a built-in JavaScript object that provides a low-level interface for reading and writing multiple numeric types (signed/unsigned integers, floats, etc.) from an ArrayBuffer at specific byte offsets, with control over endianness (byte order).
It is particularly useful when working with binary data from files, network protocols (WebSockets, fetch with arrayBuffer()), WebGL, WebAssembly, or any situation where you need precise control over binary layout.
1. Why DataView?
- Typed Arrays (
Int32Array,Uint8Array, etc.) are great for homogeneous data but have fixed endianness based on the platform and limited flexibility. - DataView lets you:
- Read/write different data types at arbitrary byte offsets.
- Explicitly choose little-endian or big-endian.
- Work safely with mixed data formats (common in file formats like PNG, WAV, or protocols like TCP/IP).
2. Creating a DataView
// Create an ArrayBuffer (raw binary memory) const buffer = new ArrayBuffer(16); // 16 bytes // Create DataView from the buffer const view = new DataView(buffer); // You can also create from a portion of the buffer const partialView = new DataView(buffer, 4, 8); // start at byte 4, length 8 bytes
3. Core Methods
DataView provides getXXX and setXXX methods for each data type:
| Method | Bytes | Signed? | Range (signed) | Range (unsigned) |
|---|---|---|---|---|
Int8 / Uint8 |
1 | Yes/No | -128 to 127 | 0 to 255 |
Int16 / Uint16 |
2 | Yes/No | -32,768 to 32,767 | 0 to 65,535 |
Int32 / Uint32 |
4 | Yes/No | -2^31 to 2^31-1 | 0 to 2^32-1 |
Float32 |
4 | Yes | ~±3.4e38 | - |
Float64 |
8 | Yes | ~±1.8e308 | - |
BigInt64 / BigUint64 |
8 | Yes/No | Very large integers | Very large integers |
Signature:
view.getInt32(byteOffset, littleEndian) // littleEndian defaults to false (big-endian) view.setInt32(byteOffset, value, littleEndian)
4. Basic Example
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
// Writing data
view.setInt8(0, 42); // byte 0
view.setUint16(1, 0xABCD, true); // bytes 1-2, little-endian
view.setFloat32(4, 3.14, false); // bytes 4-7, big-endian
// Reading data
console.log(view.getInt8(0)); // 42
console.log(view.getUint16(1, true));