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


Node.js Buffer.readIntBE()用法及代碼示例

Buffer.readIntBE()方法用於讀取給定偏移量的緩衝區的字節數,並將結果解釋為二進製補碼值。

用法:

buffer.readIntBE( offset, byteLen )

參數:此方法接受上述和以下所述的兩個參數:偏移量:它指定緩衝區對象的位置。它表示開始讀取之前要跳過的字節數。 offset的值介於0到buffer.length-byteLen之間。 byteLen:這是一個整數值,指示要從給定偏移量讀取的字節數。該參數值在0到6之間。


返回值:它從big endian中指定的偏移量返回一個帶有byteLen字節的整數值。

範例1:

// Node.js program to demonstrate the 
// buffer.readIntBE(offset, bytelen) method  
const buff = Buffer.from([0x11, 0x12, 0x34, 0x56, 0x89, 0xcd]); 
  
console.log(buff.readIntBE(0, 5).toString(16)); 
  
console.log(buff.readIntBE(0, 4).toString(16));

輸出:

1112345689
11123456

範例2:

// Node.js program to demonstrate the 
// buffer.readIntBE(offset, bytelen) method  
const buff = Buffer.from([0x11, 0x12, 0x34, 0x56, 0x89, 0xcd]); 
  
console.log(buff.readIntBE(4, 6).toString(16)); 
  
console.log(buff.readIntBE(3, 0).toString(16));

輸出:

buffer.js:831
    throw new RangeError('Index out of range');
    ^

RangeError:Index out of range
    at checkOffset (buffer.js:831:11)
    at Buffer.readIntBE (buffer.js:938:5)
    at Object. (/home/cg/root/8545664/main.js:8:17)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)

上麵的示例顯示了錯誤,因為其參數不在有效範圍內。

注意:

  • 要獲取Little Endian格式的值,可以使用Buffer.readIntLE()方法。
  • 上麵的程序將通過使用node index.js命令。

參考: https://nodejs.org/api/buffer.html#buffer_buf_readintbe_offset_bytelength



相關用法


注:本文由純淨天空篩選整理自bestharadhakrishna大神的英文原創作品 Node.js | Buffer.readIntBE() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。