DataView: byte offsets and endianness
Quick answer
DataView reads and writes numeric fields at byte offsets. It is useful for binary formats whose fields have different widths or explicit byte order.
How it works
Use new DataView(buffer) and methods such as getUint16(offset,littleEndian) and setUint16(offset,value,littleEndian). The default is big-endian (most significant byte first). Pass true for little-endian. DataView permits unaligned offsets but throws RangeError when a field extends past the view. Choose widths and byte order from the format specification.
Local examples
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const v=new DataView(new Uint8Array([1,2]).buffer);console.log(v.getUint16(0),v.getUint16(0,true));})()Expected console output:
258 513The same bytes have different meanings under different ordering.
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const b=new ArrayBuffer(3);new DataView(b).setUint16(1,258,true);console.log(JSON.stringify([...new Uint8Array(b)]));})()Expected console output:
[0,2,1]Little-endian stores the low byte first at the given offset.
Common mistakes
Do not rely on machine endianness when parsing a wire format. Explicitly choose the byte order for each multi-byte field.
Practice
Encode the unsigned number 258 in both orders and decode each using the matching order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
DataView: byte offsets and endianness — Knowledge Check
Apply the concept and reason about local example output.
What is the default endianness for DataView.getUint16?
How is a DataView offset measured?
What happens if a complete field exceeds the view bounds?
What is the expected console output of DataView: byte offsets and endianness example 1?
(async () => {const v=new DataView(new Uint8Array([1,2]).buffer);console.log(v.getUint16(0),v.getUint16(0,true));})()What is the expected console output of DataView: byte offsets and endianness example 2?
(async () => {const b=new ArrayBuffer(3);new DataView(b).setUint16(1,258,true);console.log(JSON.stringify([...new Uint8Array(b)]));})()