What is swap64() in Node.js Buffer Module?

The swap64 function in Node.js Buffer Module

The swap64 function is a member function of Buffer class in the Node.js Buffer Module. The swap64 function is used to swap the byte order in place of a Buffer instance by considering it a 64-bit (or 8 bytes) array. The syntax of the swap64 function is as follows:

buf.swap64()

Parameters

swap64 takes no parameters.

Return value

  • Returns a reference to buf of type Buffer.

Description

The swap64 function reverses every 8-byte group present in the buffer buf by treating the buf as a 64-bit (or 8 bytes) array.

Example usage of the swap64 function

The following code snippet provides an example of how to use the swap64 function:

const b = Buffer.from([0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7]);
console.log("Buffer before swap64:")
console.log(b);
b.swap64();
console.log("Buffer after swap64:")
console.log(b);

In the example above, the first group of 4 bytes (00, 01, 02, 03, 04, 05, 06, 07) is reversed, resulting in the order 07, 06, 05, 04, 03, 02, 01, 00.

If the number of bytes is not enough to form 8-byte groups, then ERR_INVALID_BUFFER_SIZE error is thrown. Below is an example:

const b = Buffer.from([0x0, 0x1, 0x2, 0x3, 0x4, 0x5]);
console.log("Buffer before swap64:")
console.log(b);
b.swap64();
console.log("Buffer after swap64:")
console.log(b);

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved