buf.swap16()
- 返回值:<Buffer> 对
buf的引用。
将 buf 解释为无符号 16 位整数数组,并就地交换字节顺序。如果 buf.length 不是 2 的倍数,则抛出 ERR_INVALID_BUFFER_SIZE。
【Interprets buf as an array of unsigned 16-bit integers and swaps the
byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length
is not a multiple of 2.】
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap16();
console.log(buf1);
// Prints: <Buffer 02 01 04 03 06 05 08 07>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.const { Buffer } = require('node:buffer');
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>
buf1.swap16();
console.log(buf1);
// Prints: <Buffer 02 01 04 03 06 05 08 07>
const buf2 = Buffer.from([0x1, 0x2, 0x3]);
buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.buf.swap16() 的一个方便用途是实现 UTF-16 小端和 UTF-16 大端之间的快速原地转换:
【One convenient use of buf.swap16() is to perform a fast in-place conversion
between UTF-16 little-endian and UTF-16 big-endian:】
import { Buffer } from 'node:buffer';
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.const { Buffer } = require('node:buffer');
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.