📜  Node.js Buffer.writeInt32BE() 方法

📅  最后修改于: 2022-05-13 01:56:33.341000             🧑  作者: Mango

Node.js Buffer.writeInt32BE() 方法

Buffer.writeInt32BE() 方法是 Buffer 模块中 Buffer 类的内置应用程序接口,用于将整数值以大端格式写入指定偏移量的缓冲区,整数值应为有效的有符号 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);

输出:

示例 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);

输出:

示例 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 and <= 4. Received 5
. . .

参考: https://nodejs.org/api/buffer.html#buffer_buf_writeint32be_value_offset