📜  Node.js Buffer.readUIntLE() 方法

📅  最后修改于: 2022-05-13 01:56:43.447000             🧑  作者: Mango

Node.js Buffer.readUIntLE() 方法

Buffer.readUIntLE() 方法是 Buffer 模块中 Buffer 类的内置应用程序编程接口,用于从指定偏移量的分配缓冲区中读取指定数量的字节值。

句法:

Buffer.readUIntLE( offset, byteLength )

参数:此方法接受上面提到的两个参数,如下所述:

  • 偏移量:它指定在读取之前要跳过的字节数,或者只是表示缓冲区中的索引。 offset 的值是0 <= offset <= Buffer.length – byteLength 。它的默认值为 0。
  • byteLength:指定要读取的字节数。 byteLength 的值是0 < byteLength <= 6

返回值:此方法返回一个整数值,它以 Little Endian 格式从缓冲区读取。

下面的示例说明了 Node.js 中 Buffer.readUIntLE() 方法的使用:

示例 1:

// Node program to demonstrate the  
// Buffer.readUIntLE() 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.readUIntLE(0, 3).toString(16));
console.log(buf.readUIntLE(1, 3).toString(16));
console.log(buf.readUIntLE(2, 2).toString(16));

输出:


190921
981909
9819

示例 2:

// Node program to demonstrate the  
// Buffer.readUIntLE() 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.readUIntLE(0, 3).toString(16));
console.log(buf.readUIntBE(0, 3).toString(16));
console.log(buf.readUIntLE(1, 2).toString(16));
console.log(buf.readUIntBE(1, 2).toString(16));
console.log(buf.readUIntLE(2, 1).toString(16));
console.log(buf.readUIntBE(2, 1).toString(16));

输出:


190921
210919
1909
919
19
19

示例 3:

// Node program to demonstrate the  
// Buffer.readUIntLE() 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.readUIntLE(0, 4).toString(16));
console.log(buf.readUIntLE(1, 2).toString(16));
console.log(buf.readUIntLE(2, 3).toString(16));
   
// Wrong index is provoded to produce error
console.log(buf.readUIntLE(3, 6).toString(16));

输出:


98190921
1909
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 readUInt24LE (internal/buffer.js:118:5)
    at Buffer.readUIntLE (internal/buffer.js:61:12)
    . . .

注意:以上程序将使用node index.js命令编译运行。

参考: https://nodejs.org/api/buffer.html#buffer_buf_readuintle_offset_bytelength