DataView.prototype.setInt8()
is a method in JavaScript that takes an 8-bit integer value and sets it at the specified byte offset from the start of the DataView
object.
The syntax of the setInt8()
method is:
setInt8(byteOffset : Number, value : Number, [littleEndian = false : Boolean]): void
byteOffset
: A number that specifies the byte offset from the start of the view.
value
: An 8-bit integer that is stored at the specified byte offset.
littleEndian
: An optional parameter that specifies whether the 8-bit integer is stored in the little-endian format or the big-endian format. By default, this value is False
, meaning 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 ArrayBuffer
, we need something called view
objects.
View
objectsView
objects do not store any data, instead they 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 great flexibility to interpret the buffer.
We can use DataView
objects to access the data in any format we want and at any offset. Moreover, the format in which data is interpreted is done at method call time.
DataView
The syntax to declare a DataView
object is:
new DataView(buffer, [byteOffset], [byteLength])
buffer
: The ArrayBuffer
object that contains 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 that we have an idea of binary data in JavaScript and how to declare DataView
objects, let’s look at how we can use dataView.setInt8()
in a program.
buffer = new ArrayBuffer(12);let dataView = new DataView(buffer);dataView.setInt8(1, 255)console.log(dataView.getInt8(1))
In the example above, we declare an ArrayBuffer
with a length of 12-bytes.
We create the object dataView
with the constructor of the DataView
class and pass the buffer
object to it.
We use the dataView.setInt8(1, 255)
function to store the value 255
in the 8-bits after the first byte from the start of the view.
We use the dataView.getInt8(1)
method to verify that the value has been successfully set in the buffer.