Node.js Buffer.readUIntBE() 方法
Buffer.readUIntBE() 方法是 Buffer 模块内的 Buffer 类的内置应用程序编程接口,用于从指定偏移量的已分配缓冲区中读取指定数量的字节值。
句法:
Buffer.readUIntBE( offset, byteLength )
参数:此方法接受上面提到的两个参数,如下所述:
- 偏移量:它指定在读取之前要跳过的字节数,或者只是表示缓冲区中的索引。 offset 的值是0 <= offset <= Buffer.length – byteLength 。它的默认值为 0。
- byteLength:指定要读取的字节数。 byteLength 的值 loes 0 < byteLength <= 6 。
返回:此方法返回一个整数值,它以大端格式从缓冲区读取。
下面的示例说明了 Node.js 中 Buffer.readUIntBE() 方法的使用:
示例 1:
// Node program to demonstrate the
// Buffer.readUIntBE() Method
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
// Printing allocated buffer
console.log(buf);
// Reading data from the buffer
// and printing it as a string
console.log(buf.readUIntBE(0, 3).toString(16));
console.log(buf.readUIntBE(1, 3).toString(16));
console.log(buf.readUIntBE(2, 2).toString(16));
输出:
210919
91998
1998
示例 2:
// Node program to demonstrate the
// Buffer.readUIntBE() Method
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
// Printing allocated buffer
console.log(buf);
// Reading data from the buffer
// and printing it as a string
console.log(buf.readUIntBE(0, 3).toString(16));
console.log(buf.readUIntLE(0, 3).toString(16));
console.log(buf.readUIntBE(1, 2).toString(16));
console.log(buf.readUIntLE(1, 2).toString(16));
console.log(buf.readUIntBE(2, 1).toString(16));
console.log(buf.readUIntLE(2, 1).toString(16));
输出:
210919
190921
919
1909
19
19
示例 3:
// Node program to demonstrate the
// Buffer.readUIntBE() Method
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
// Printing allocated buffer
console.log(buf);
// Reading data from the buffer
// and printing it as a string
console.log(buf.readUIntBE(0, 4).toString(16));
console.log(buf.readUIntBE(1, 2).toString(16));
console.log(buf.readUIntBE(2, 3).toString(16));
// Wrong index is provoded to produce error
console.log(buf.readUIntBE(3, 6).toString(16));
输出:
21091998
919
internal/buffer.js:49
throw new ERR_OUT_OF_RANGE(type || 'offset',
^
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range.
It must be >= 0 and <= 1. Received 2
at boundsError (internal/buffer.js:49:9)
at readUInt24BE (internal/buffer.js:205:5)
at Buffer.readUIntBE (internal/buffer.js:148:12)
. . .
注意:以上程序将使用node index.js
命令编译运行。
参考: https://nodejs.org/api/buffer.html#buffer_buf_readuintbe_offset_bytelength