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


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


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

用法:

Buffer.readUIntBE( offset, byteLength )

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


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

返回:此方法以Big Endian格式返回从缓冲区读取的整数值。

以下示例说明了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));

输出:

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

输出:

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

输出:

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



相关用法


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