Buffer.writeInt32BE()方法是Buffer模塊中Buffer類的內置應用程序編程接口,用於將整數值寫入具有big-endian格式的指定偏移量的緩衝區,該整數值應為有效的帶符號32位整數。如果該值超出32位有符號整數的範圍,則會引發錯誤。整數值將被解釋並寫入為兩個補碼有符號整數。
用法:
Buffer.writeInt32BE( value, offset )
參數:該方法接受上述和以下所述的兩個參數:
value:此參數保存一個需要寫入緩衝區的32位帶符號整數。
offset:此參數保存一個整數值,即在開始寫入緩衝區之前要跳過的字節數。 offset的值介於0到buf.length-4之間。它是一個可選參數,默認值為0。
返回值:此方法返回一個整數值,即偏移量與寫入的字節數之和。
以下示例說明了在Node.js中使用buf.writeInt32BE()方法:
範例1:
// Node.js program to demonstrate the
// Buffer.writeInt32BE() Method
// Allocating buffer space of 4 bytes
const buf = Buffer.allocUnsafe(4);
// Writing the value to the buffer
buf.writeInt32BE(0x7bcaf892);
// Display the buffer to stdout
console.log(buf);
輸出:
<Buffer 7b ca f8 92>
範例2:
// Node.js program to demonstrate the
// Buffer.writeInt32BE() Method
// Allocating buffer space of 8 bytes
const buf = Buffer.allocUnsafe(8);
// Writing the value to the buffer from 0 offset
buf.writeInt32BE(0x7bcaf983, 0);
// Writing the value to the buffer from 4 offset
buf.writeInt32BE(0x7fffffff, 4);
// Display the buffer to stdout
console.log(buf);
輸出:
<Buffer 7b ca f9 83 7f ff ff ff>
範例3:此示例將顯示一條錯誤消息,因為偏移量大於限製,即偏移量值不在0到buf.length-4之間。
// Node.js program to demonstrate the
// Buffer.writeInt32BE() Method
// Allocating buffer space of 8 bytes
const buf = Buffer.allocUnsafe(8);
// Writing the value to the buffer from 0 offset
buf.writeInt32BE(0x7bcaf983, 0);
// Writing the value to the buffer from 4 offset
buf.writeInt32BE(0x7fffffff, 5);
// Display the buffer to stdout
console.log(buf);
輸出:
internal/buffer.js:72 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 andReference: https://nodejs.org/api/buffer.html#buffer_buf_writeint32be_value_offset
相關用法
注:本文由純淨天空篩選整理自akshajjuneja9大神的英文原創作品 Node.js | Buffer.writeInt32BE() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。