javascript / expert
Snippet
Binary Protocol Parsing with DataView
DataView provides a low-level interface for reading and writing multiple number types in an ArrayBuffer, regardless of the platform's endianness. This is critical when implementing custom network protocols or file parsers where specific byte orders (Big-Endian vs Little-Endian) are required.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
const buffer = new ArrayBuffer(16);const view = new DataView(buffer);// Set a 32-bit float at offset 0, little-endianview.setFloat32(0, 3.14159, true);// Set a 16-bit unsigned int at offset 4, big-endianview.setUint16(4, 0xABCD, false);console.log(view.getFloat32(0, true)); // 3.14159
nodejs
Breakdown
1
new DataView(buffer);
Creates a view that allows granular access to the underlying binary data.
2
view.setUint16(4, 0xABCD, false);
Writes a 16-bit integer at byte 4 using Big-Endian order (false).