Node.js Buffer.swap16(), swap32(), swap64() Method



The Buffer.swap16(), Buffer.swap32(), Buffer.swap64() method considers the buffer as an array of unsigned 16 or 32 or 64 bit integers and swaps the byte order in-place and returns a reference to the buffer.

Please note for −

Buffer.swap16(), it will throw an error called ERR_INVALID_BUFFER_SIZE if the buffer length is not a multiple of 2.

Buffer.swap32(), it will throw an error called ERR_INVALID_BUFFER_SIZE if the buffer length is not a multiple of 4.

Buffer.swap64(), it will throw an error called ERR_INVALID_BUFFER_SIZE if the buffer length is not a multiple of 8.

Syntax

Following is the syntax of the Node.JS Buffer.swap16(), Buffer.swap32(), Buffer.swap64() Method −

buf.swap16()
buf.swap32()
buf.swap64()

Parameters

This method does not accept any parameters.

Return value

The method buffer.swap16(), buffer.swap32(), buffer.swap64() returns a reference to the buffer used by swapping the byte order in-place.

Example

To create a buffer, we are going to make use of NodeJS Buffer.from() method −

const buf1 = Buffer.from([11, 12, 13, 14, 15, 16]);
console.log(buf1);
const buf2 = buf1.swap16();
console.log(buf2);

Output

In above we have used NodeJS buf.swap16() and the same returns a reference to the buffer used.

<Buffer 0b 0c 0d 0e 0f 10>
<Buffer 0c 0b 0e 0d 10 0f>

Example

To create a buffer, we are going to make use of NodeJS Buffer.from() method −

const buf1 = Buffer.from([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]);
console.log(buf1);
const buf2 = buf1.swap32();
console.log(buf2);

Output

In above we have used NodeJS buf.swap32() and the same returns a reference to the buffer used.

<Buffer 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10>
<Buffer 04 03 02 01 08 07 06 05 0c 0b 0a 09 10 0f 0e 0d>

Example

To create a buffer, we are going to make use of Buffer.from() method −

const buf1 = Buffer.from([1,2,3,4,5,6,7,8]);
console.log(buf1);
const buf2 = buf1.swap64();
console.log(buf2);

Output

In above we have used NodeJS buf.swap64() and the same returns a reference to the buffer used.

<Buffer 01 02 03 04 05 06 07 08>
<Buffer 08 07 06 05 04 03 02 01>
nodejs_buffer_module.htm
Tutorix - AI Tutor
Advertisements
8