Course contentsShow
← JavaScript
Lesson 2339 of 2,72348. Working with Binary DataFree lesson

Endianness in DataView

Understanding little-endian vs big-endian byte order and how to specify it in DataView get/set methods.

Endianness in DataView

You'll learn how to control byte order when reading and writing multi-byte values in a DataView.

What is Endianness?

When a multi-byte value (like a 16-bit integer) is stored in memory, the bytes can be ordered in two ways:

  • Big-endian: Most significant byte first (like reading left-to-right: the "big" part comes first)
  • Little-endian: Least significant byte first (the "little" part comes first)

Think of it like writing a number: in big-endian, 0x1234 is stored as 12 34, but in little-endian it's stored as 34 12.

Specifying Endianness in DataView

All DataView get and set methods (except for single-byte methods like getInt8 or setUint8) accept an optional second parameter to specify byte order:

const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);

// Write a 16-bit value (0x1234)
view.setUint16(0, 0x1234, true);  // true = little-endian
view.setUint16(0, 0x1234, false); // false = big-endian (default)

// Read with different endianness
const bigEndian = view.getUint16(0, false);    // default
const littleEndian = view.getUint16(0, true);

Default behavior: If you omit the second parameter, DataView uses big-endian (network byte order).

Why This Matters

Different systems and file formats use different byte orders. DataView's explicit endianness control lets you work with binary data from any source without worrying about your machine's native byte order.

Key Takeaway: DataView methods take an optional boolean parameter (true for little-endian, false or omitted for big-endian) to control how multi-byte values are stored and retrieved from the buffer.