Buffer.writeInt8()方法是Buffer模塊中Buffer類的內置應用程序編程接口,用於將值以指定的偏移量寫入分配的緩衝區。
用法:
Buffer.writeInt8( value, offset )
參數:該方法接受上述和以下所述的兩個參數:
- value:此參數指定要寫入緩衝區的數字或值。當值不是整數值時,行為是不確定的。
- offset:它指定開始寫入之前要跳過的字節數,或者隻是表示緩衝區中的索引。 offset的值為0
返回值:此方法返回一個整數值,該值是偏移量和寫入的字節數的總和。
以下示例說明了Node.js中Buffer.writeInt8()方法的使用:
範例1:
// Node.js program to demonstrate the
// Buffer.writeInt8() method
// Allocating buffer of size 4
const buf = Buffer.allocUnsafe(4);
// Writing 8 bit numbers to its
// specified offset and printing
// returned value to console
console.log(buf.writeInt8(20, 0));
console.log(buf.writeInt8(-128, 1));
console.log(buf.writeInt8(-3, 2));
console.log(buf.writeInt8(127, 3));
// Printing buffer to console
console.log(buf);
輸出:
1 2 3 4 <Buffer 14 80 fd 7f>
範例2:
// Node.js program to demonstrate the
// Buffer.writeInt8() method
// Allocating buffer of size 2
const buf = Buffer.allocUnsafe(2);
// Printing the buffer before writing into it
console.log("Before writing into buffer:");
console.log(buf);
// Writing 8 bit signed integers
console.log(buf.writeInt8(96, 0));
console.log(buf.writeInt8(-69, 1));
// Printing buffer after writing
// 8 bit signed integers in it.
console.log("After writing into buffer:");
console.log(buf);
輸出:
Before writing into buffer: <Buffer 98 98gt; 1 2 After writing into buffer: <Buffer 60 bb>
注意:上麵的程序將通過使用node index.js
命令。
參考: https://nodejs.org/api/buffer.html#buffer_buf_writeint8_value_offset
相關用法
注:本文由純淨天空篩選整理自gekcho大神的英文原創作品 Node.js | Buffer.writeInt8() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。