Open In App
Related Articles

Node.js Buffer.writeInt32BE() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
The Buffer.writeInt32BE() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to write integer value to buffer at the specified offset with the big-endian format, integer value should be a valid signed 32-bit integer. Error is thrown if the value is outside the range of signed 32-bit integer.Integer value is interpreted and written as a two’s complement signed integer. Syntax:
Buffer.writeInt32BE( value, offset )
Parameters: This method accept two parameters as mentioned above and described below: value: This parameter holds a 32-bit signed integer that need to be written to the buffer. offset: This parameter holds an integer value i.e. the number of bytes to skip before starting to write into the buffer. The value of offset lies between 0 to buf.length – 4. It is an optional parameter and its default value is 0. Return Value: This method returns an integer value i.e. the sum of offset plus the number of bytes written. Below examples illustrate the use of buf.writeInt32BE() method in Node.js: Example 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);

                    
Output:
<Buffer 7b ca f8 92>
Example 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);

                    
Output:
<Buffer 7b ca f9 83 7f ff ff ff>
Example 3: This example will display an error message because the offset is greater than the limit i.e. the offset value does not lies within 0 to 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);

                    
Output:
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
. . .
Reference: https://nodejs.org/api/buffer.html#buffer_buf_writeint32be_value_offset

Last Updated : 13 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads