當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。