The DataView.prototype.setUint32()
is a method in JavaScript that takes an unsigned 32-bit integer value and sets this value at the specified byte offset from the start of the DataView
object.
The syntax of the method is as follows:
setUint32(byteOffset : Number, value : Number, [littleEndian = false : Boolean]): void
–
byteOffset
: A Number
specifying the byte offset from the start of the view.
value
: A unsigned 32-bit integer that will be stored at the specified byte offset.
littleEndian
: An optional parameter specifying whether the 16-bit integer is stored in the little-endian format or the big-endian format.
By default, the value is
False
, which means a big-endian value is stored.
DataView
classWhile many languages provide byte arrays to manipulate binary data, things work differently in JavaScript.
The most fundamental binary object in JavaScript is the ArrayBuffer
, which stores a reference to a fixed-length contiguous memory space that contains a raw sequence of bytes.
However, to interpret and manipulate the ArrayBuffer
, we need something called view objects.
View objects themselves do not store any data, but rather provide the different interfaces to read and write byte data in the raw buffer.
The DataView
class is one such view over the ArrayBuffer
that provides flexibility in interpreting the buffer.
By using DataView
objects, we can access the data in any format we like and at any offset. Moreover, the format in which data is interpreted is done at the method call time.
DataView
The syntax to declare a DataView
object is as follows:
new DataView(buffer, [byteOffset], [byteLength])
buffer
: The ArrayBuffer
object containing the raw sequence of bytes.
byteOffset
: The starting byte position of the view from the starting position of ArrayBuffer
. The default value is 0.
byteLength
: The byte length that will be viewed from the specified byteOffset
. By default, the whole buffer is viewed.
Now we have some idea of binary data in JavaScript and declaring DataView
objects.
Let’s look at how can we use dataView.setUint32()
in a program.
buffer = new ArrayBuffer(12);let dataView = new DataView(buffer);dataView.setUint32(1,4294967295)console.log(dataView.getUint32(1))
In the example above, we declare an ArrayBuffer
with length of 12 bytes.
We create the object dataView
using the constructor of the DataView
class and pass the buffer
object to it.
Using the dataView.setUint32(1, 4294967295)
function call, we store the value 4294967295
in the 32 bits after the first byte from the start of the view.
Using the dataView.getUint32(1)
method, we verify that the value has been set successfully in the buffer.