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


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

Buffer.writeUIntLE()方法用於使用Little Endian將指定的字節寫入Buffer對象。它支持高達48位的精度。當您使用無符號整數以外的任何值時,其行為是不確定的。

用法:

Buffer.writeUIntLE( value, offset, byteLength )

參數:此方法接受上述和以下所述的三個參數:


  • value:它指定需要寫入Buffer對象的編號。
  • offset:它指定開始寫入緩衝區之前要跳過的字節數。 offset的值為0
  • byteLength:它指定要寫入緩衝區的字節數。 byteLength的值為0

返回值:它返回偏移量加上寫入的字節數。

以下示例說明了Node.js中Buffer.writeUIntLE()方法的使用:

範例1:

// Node.js program to demonstrate the   
// Buffer.writeUIntLE() method  
   
// Creating a buffer of size 4  
const buffer_1 = Buffer.allocUnsafe(4); 
   
// Writes byteLength bytes of value to buf 
// at the specified offset. 
buffer_1.writeUIntLE(0x12127474, 0, 4); 
   
// Display the result  
console.log(buffer_1); 
   
// Creating a buffer of size 6 
const buffer_2 = Buffer.allocUnsafe(6); 
buffer_2.writeUIntLE(0x12127474abcd, 0, 6); 
   
// Display the result  
console.log(buffer_2);

輸出:

<Buffer 74 74 12 12>
<Buffer cd ab 74 74 12 12>

範例2:

// Node.js program to demonstrate the   
// Buffer.writeUIntLE() method  
   
// Creating a buffer of given size  
const buffer = Buffer.allocUnsafe(8); 
//Before writing anything 
console.log("Before filling buffer"); 
console.log(buffer); 
   
// to fill first 6 bytes, take offset 0 
// and bytelength 6 
console.log("After filling 6 bytes"); 
buffer.writeUIntLE(0xcc1267280012, 0, 6); 
console.log(buffer); 
   
// to fill next 2 bytes add 6 offet 
// and bytelength 2 
console.log("After filling next 2 bytes"); 
buffer.writeUIntLE(0x1112, 6, 2) 
console.log(buffer);

輸出:

Before filling buffer
<Buffer 00 00 00 00 00 00 00 00>
After filling 6 bytes
<Buffer 12 00 28 67 12 cc 00 00>
After filling next 2 bytes
<Buffer 12 00 28 67 12 cc 12 11>

注意:上麵的程序將通過使用node index.js命令。

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



相關用法


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