Buffer swap16 and swap32 Flip In-Place Byte Order
Convert multi-byte wire buffers between big-endian and little-endian in place with Node Buffer.swap16 and swap32, catching unaligned buffer lengths.
Code
import { Buffer } from 'node:buffer';
// Big-endian 16-bit header pairs: 0x0102, 0x0304
const frame16 = Buffer.from([0x01, 0x02, 0x03, 0x04]);
frame16.swap16();
console.log('swap16 hex:', frame16.toString('hex'), 'LE[0]:', frame16.readUInt16LE(0).toString(16));
// Big-endian 32-bit integer 0x12345678 swapped in place to little-endian
const frame32 = Buffer.from([0x12, 0x34, 0x56, 0x78]);
frame32.swap32();
console.log('swap32 hex:', frame32.toString('hex'), 'LE:', frame32.readUInt32LE(0).toString(16));
// Unaligned lengths throw RangeError instead of silently truncating trailing bytes
const odd = Buffer.from([0xaa, 0xbb, 0xcc]);
try {
odd.swap16();
} catch (err) {
console.log('unaligned:', err.name, err.code);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
swap16 hex: 02010403 LE[0]: 102
swap32 hex: 78563412 LE: 12345678
unaligned: RangeError ERR_INVALID_BUFFER_SIZEBehavior overview — Buffer swap16 and swap32 Flip In-Place Byte Order
Buffer comes from node:buffer — Node.js core modules the runtime ships with.
Code statements below act cleanly upon module-scope values: frame16, frame32, odd.
Watch out for
node:bufferis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Applying it
The run emits 3 labeled sections — swap16 hex:, swap32 hex:, unaligned: — one per step.
Statements that matter
const frame16 = Buffer.from([0x01, 0x02, 0x03, 0x04]);
const frame32 = Buffer.from([0x12, 0x34, 0x56, 0x78]);
const odd = Buffer.from([0xaa, 0xbb, 0xcc]);
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No — `node:buffer` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.