JavaScript Reference ยท Typed Arrays and Binary Data
The DataView object
Reference for the JavaScript DataView object: read and write integers and floats at any byte offset with explicit endianness, with live examples and notes.
A DataView reads and writes numbers at any byte position of an ArrayBuffer, with a byte order you choose for every call. Typed arrays are faster for uniform data, but they use the machine's byte order and need aligned offsets. DataView has neither limit, which makes it the right tool for file formats and network protocols where fields have mixed types and a defined endianness.
const view = new DataView(new ArrayBuffer(8)); view.setUint16(0, 0x1234); // big-endian by default view.getUint16(0, true); // read it little-endian
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
new DataView(buffer) new DataView(buffer, byteOffset) new DataView(buffer, byteOffset, byteLength) view.getUint16(byteOffset, littleEndian) view.setUint16(byteOffset, value, littleEndian)
| Name | Description |
|---|---|
buffer |
The ArrayBuffer (or SharedArrayBuffer) to read and write. |
byteOffset |
Constructor: where the view starts (default 0). Methods: the position to read or write, relative to the view's start. |
byteLength |
Size of the view in bytes. Defaults to the rest of the buffer. |
value |
The number (or BigInt) to store, converted to the target type. |
littleEndian |
true for little-endian. If omitted or false, the value is big-endian. |
Method families. Each type has a getter and a setter: Int8, Uint8, Int16, Uint16, Int32, Uint32, Float32, Float64, BigInt64, BigUint64 (for example getInt16() and setInt16()). Float16 has a pair as well in newer engines.
Properties: buffer, byteOffset, byteLength.
Return value: getters return the number (a BigInt for the 64-bit integer types); setters return undefined.
Exceptions: RangeError if the read or write would cross the end of the view, or if the constructor's offset or length do not fit in the buffer. TypeError when the first argument is not a buffer.
Usage notes
- The default is big-endian, the opposite of most machines and of typed arrays. Many formats (network order, PNG) are big-endian; many others (WAV, BMP) are little-endian. Always pass the flag explicitly when a format specifies it.
- No alignment rules. You can read a
Uint32at offset 3. - Shared memory. A
DataViewand any typed array over the same buffer see each other's writes. - Conversion on write. Out-of-range integers wrap around, like typed array elements.
- Speed. Typed arrays are usually faster for large uniform data; use
DataViewfor headers and mixed records. - Strings are not part of
DataView. Encode them with TextEncoder and copy the bytes into aUint8Arrayview.
Browser support
DataView works in all current browsers. The Float16 accessors are recent, so check a compatibility table for them.