Files and data

Read a binary integer with an explicit byte order

Use DataView when a binary format specifies integer widths and byte order. Pass the endianness flag deliberately instead of assuming the host machine’s native layout matches the format.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const bytes = new Uint8Array([1, 0, 0, 0]);
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
console.log(view.getUint32(0, true));
console.log(view.getUint32(0, false));

How it works

True selects little-endian interpretation, so the first byte is the least significant and the value is one. False selects big-endian interpretation, giving 16777216. Both read the same bytes; the format’s contract determines which is meaningful.

Limits and mistakes

Check length before reading a field because an out-of-range access throws. A typed-array slice can have a nonzero byte offset, so include it when constructing the view. Signedness and field width also need to match the format.

Check the result

Expect 1 and 16777216. Use a fixture from the actual file specification and test a truncated input to confirm it produces a controlled validation error.

Sources

Reference documentation for the behavior used in this guide: