Node.js Reference ยท Buffers and Encoding
Node.js buf.swap16(), swap32() and swap64() methods
Reference for Node.js buf.swap16(), swap32() and swap64(): reverse the byte order of every 2, 4 or 8 byte element in place to convert between big and little endian.
buf.swap16(), buf.swap32() and buf.swap64() reverse the order of the bytes inside each 2-byte, 4-byte or 8-byte element of the buffer. Doing this converts a whole array of numbers between big-endian and little-endian layout in one native call, which is much faster than reading and writing each value.
The swap happens in place and the method returns the same buffer, so calls can be chained. The buffer length must be an exact multiple of the element size, or an error is thrown.
const buf = Buffer.from([1, 2, 3, 4]); buf.swap16(); // <Buffer 02 01 04 03> buf.swap32(); // <Buffer 03 04 01 02>
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
buf.swap16() // returns Buffer (buf itself) buf.swap32() buf.swap64()
These methods take no parameters.
Returns: buf, with each group of 2, 4 or 8 bytes reversed.
Errors and edge cases:
ERR_INVALID_BUFFER_SIZEwhenbuf.lengthis not a multiple of 2, 4 or 8 respectively. The message names the required multiple in bits.- An empty buffer is accepted and left unchanged.
Usage notes
- In place: the original bytes are overwritten. Make a copy first with
Buffer.from(buf)when you need both versions, as the example does. - Only whole elements: if the data has a header of an odd size, swap a
subarray()of just the numeric part. The view shares memory, so the swap affects the original. - Fast bulk conversion: use these methods before creating a
Uint16Array,Uint32ArrayorFloat64Arrayover data of the other byte order. All platforms Node.js supports are little-endian, so big-endian file data needs a swap before typed array access. swap32()andswap64()also reverse floats (4 and 8 byte values), which makesFloat32Arrayaccess to big-endian data possible.- UTF-16: Node.js decodes only
utf16le. For big-endian UTF-16 text,swap16()converts it so thattoString("utf16le")works (see Buffer encodings). - A single value is simpler with the BE and LE read methods; swapping is for arrays and blocks.
- Aligned and unaligned buffers both work; the methods do not require the buffer's memory address to be aligned.