Node.js Buffer.writeInt32BE() Method
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:
const buf = Buffer.allocUnsafe(4);
buf.writeInt32BE(0x7bcaf892);
console.log(buf);
|
Output:
<Buffer 7b ca f8 92>
Example 2:
const buf = Buffer.allocUnsafe(8);
buf.writeInt32BE(0x7bcaf983, 0);
buf.writeInt32BE(0x7fffffff, 4);
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.
const buf = Buffer.allocUnsafe(8);
buf.writeInt32BE(0x7bcaf983, 0);
buf.writeInt32BE(0x7fffffff, 5);
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
Share your thoughts in the comments
Please Login to comment...