当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js Buffer.readUIntLE()用法及代码示例


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

用法:

Buffer.readUIntLE( offset, byteLength )

参数:该方法接受上述和以下所述的两个参数:


  • offset:它指定在读取之前要跳过的字节数,或者只是表示缓冲区中的索引。 offset的值为0
  • byteLength:它指定要读取的字节数。 byteLength的值为0

返回值:此方法以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));

输出:

<Buffer 21 09 19 98>
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));

输出:

<Buffer 21 09 19 98>
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));

输出:

<Buffer 21 09 19 98>
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



相关用法


注:本文由纯净天空筛选整理自anwesha0107大神的英文原创作品 Node.js | Buffer.readUIntLE() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。