Buffer.writeInt16BE()方法是Buffer模塊中Buffer類的內置應用程序編程接口,用於將整數值寫入具有big-endian格式的指定偏移處的緩衝區。整數值應為有效的帶符號16位整數。如果該值超出帶符號的16位整數範圍,則將引發錯誤。整數值被解釋並寫入為兩個補碼有符號整數。
用法:
Buffer.writeInt16BE( value, offset )
參數:該方法接受上述和以下所述的兩個參數:
- value:它是一個16位帶符號整數,必須將其寫入緩衝區。
- offset:它是一個整數值,即開始寫入緩衝區之前要跳過的字節數。 offset的值在buf.length-2處為0。它是可選參數,默認值為0。
返回值:它返回一個整數值,該值是偏移量與寫入的字節數之和。
以下示例說明了如何在Node.js中使用buf.writeInt16BE()方法:
範例1:
// Node.js program to demonstrate the
// Buffer.writeInt16BE() Method
// Allocate a buffer
const buf = Buffer.allocUnsafe(2);
// Writing the value to the buffer
buf.writeInt16BE(0x7bca);
// Display the buffer value
console.log(buf);
輸出:
<Buffer 7b ca>
範例2:
// Node.js program to demonstrate the
// Buffer.writeInt16BE() Method
// Allocate a buffer
const buf = Buffer.allocUnsafe(4);
// Writing the value to the buffer
// from 0 offset
buf.writeInt16BE(0x7bca, 0);
// Writing the value to the buffer
// from 2 offset
buf.writeInt16BE(0x7fff, 2);
// Display the result
console.log(buf);
輸出:
<Buffer 7b ca 7f ff>
範例3:
// Node.js program to demonstrate the
// Buffer.writeInt16BE() Method
// Allocate a buffer
const buf = Buffer.allocUnsafe(4);
// Writing the value to the buffer
// from 0 offset
buf.writeInt16BE(0x7bca, 0);
// Writing the value to the buffer
// from 2 offset
buf.writeInt16BE(0x7fff, 3);
// Display the result
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_writeint16be_value_offset
相關用法
注:本文由純淨天空篩選整理自akshajjuneja9大神的英文原創作品 Node.js | Buffer.writeInt16BE() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。