JavaScript DataView setInt16() Method



The JavaScript DataView setInt16() method stores a number value as a 16-bit signed integer in the 2 bytes, starting at a specified byte offset of this DataView. Multiple bytes can be stored at any offset within the bounds.

If the number value is not in the range of -32768 to 32767, it will not store the value in this DataView, and if the byteOffset parameter value is outside the bounds of this DataView, it will throw a 'RangeError' exception.

Syntax

Following is the syntax of the JavaScript DataView setInt16() method −

setInt16(byteOffset, value, littleEndian)

Parameters

This method aceepts three parameters named 'byteOffset', 'value', and 'littleEndian', which are described below −

  • byteOffset − The position in the DataView where the byte will be stored.
  • value − A signed 16-bit integer that needs to be stored.
  • littleEndian − It indicates whether the data value is stored in little- or big-endian format.

Return value

This method returns'undefined', as it only stores a byte value.

Example 1

The following program demonstrates the usage of the JavaScript DataView setInt16() method.






Output

The above program returns 'undefined' −

Value: 255
The byte offset: 1
The data_view.setInt16() method returns: undefined

Example 2

If the data value falls outside the range of-32768 to 32767, thesetInt16()method will not store the specified value as it exceeds the range for an 8-bit signed integer.






Output

After executing the program, the data value will not be stored since it is outside the range of acceptable values −

Value: 327678
The byte offset: 0
The store value: -33554432

Example 3

If the value of the byteOffset parameter is outside the bounds of this data view, it will throw a 'RangeError' exception.






Output

Once the above program is executed, it will throw a 'RangeError' exception as −

Value: 300
The byte offset: -2
RangeError: Offset is outside the bounds of the DataView
Advertisements