What is the Buffer.writeUint32LE() method in Node.js?
The Buffer.writeUint32() method in Node.js is used to write a 32-bit Unsigned Integer value to a specific location in the buffer in the little-endian format.
Endianness
The endianness of data refers to the order of bytes in the data. There are two types of Endianness:
-
Little Endian stores the Least Significant Byte (LSB) first. It is commonly used in Intel processors.
-
Big Endian stores the Most Significant Byte (MSB) first. It is also called Network Byte Order because most networking standards expect the MSB first.
writeUint32LEis also an alias of this function.
Syntax
buf.writeUInt32LE(value[, offset])
Parameters
-
value: The value of the unsigned integer to be written to the buffer. -
offset: The offset from the starting position where thevaluewill be written. The default value foroffsetis .The
offsetmust be between andbuffer.length - 4.
Return value
buffer.writeUInt32LE() returns the offset plus the number of bytes written to the buffer.
Exceptions
The behavior of buffer.writeUInt32LE() is undefined if the value is anything other than a 32-bit unsigned Integer.
Code
const buf = Buffer.alloc(4);buf.writeUInt32LE(0xff000032);console.log(buf)
Explanation
-
The first line in the code creates a buffer called
bufand allocates 4 bytes of memory to it. -
Next, we write the value
0xff000032which is a 32 bit integer value where the MSB is0xffand the LSB is 0x32, using the following line:
buf.writeUInt32LE(0xff000032);
- In the last line, we print out the contents of the buffer to the Standard Output.
As we can see, the contents are printed in the little-endian format where the least significant byte is stored first and the most significant byte is stored last.