The DataView makes no assumptions about what data type is stored inside the buffer.
We must specify an ElementType when reading or writing.
DataView will perform the conversion to execute that read or write.
Javascript 6 supports eight different ElementTypes:
Elementtype | Bytes | Description | C Equivalent | Range Of Values |
---|---|---|---|---|
Int8 | 1 | 8-bit signed integer | signed char | -128 to 127 |
Uint8 | 1 | 8-bit unsigned integer | unsigned char | 0 to 255 |
Int16 | 2 | 16-bit signed integer | short | -32768 to 32767 |
Uint16 | 2 | 16-bit unsigned integer | unsigned short | 0 to 65535 |
Int32 | 4 | 32-bit signed integer | int | -2,147,483,648 to 2,147,483,647 |
Uint32 | 4 | 32-bit unsigned integer | unsigned int | 0 to 4,294,967,295 |
Float32 | 4 | 32-bit IEEE-754 floating point | float | -3.4E+38 to +3.4E+38 |
Float64 | 8 | 64-bit IEEE-754 floating point | double | -1.7E+308 to +1.7E+308 |
The DataView exposes get and set methods for each of these types.
It uses a byteOffset
to address the buffer for reading and writing values.
// Allocate two bytes of memory and declare a DataView const buf = new ArrayBuffer(2);//w w w . j ava 2 s . c o m const view = new DataView(buf); console.log(view.getInt8(0)); // 0 console.log(view.getInt8(1)); // 0 console.log(view.getInt16(0)); // Check the entire buffer // Set the entire buffer to ones 255 in binary is 11111111 (2^8 - 1) view.setUint8(0, 255); // DataView casts values to the designated Element Type, 255 in hex is 0xFF view.setUint8(1, 0xFF); // read as a two's complement signed integer should be -1 console.log(view.getInt16(0)); // -1