About
To manipulate a byte array, in javascript, you have:
- a ArrayBuffer 1) that represents an array:
- of fixed amount of bytes (one element = 1 byte)
- of binary element known as typed object 2):
- Int8 / Uint8: 8-bit two's complement signed or unsigned integer
- Int16 / Uint16: 16-bit two's complement signed or unsigned integer
- Int32 / Uint32: 32-bit two's complement signed or unsigned integer
- BigInt64 / BigUint64: 64-bit two's complement signed or unsigned integer
- Float32 / Float64: 32-bit IEEE floating point/64-bit IEEE floating point
- a DataView 3) that
- permits to read and write into the ArrayBuffer without having to care about the platform's endianness.
Example
ArrayBuffer and DataView
- an array of byte of length 9
let byteLength = 9; // the length of the array (in bytes)
let buffer = new ArrayBuffer(byteLength);
console.log(`byteLength: the length of the ArrayBuffer is ${buffer.byteLength} byte`);
- Wrapped in view that lets you manipulate the ArrayBuffer content
let viewStartByteOffset = 0; // default to 0, same as view.toIndex(byteOffset), immutable
let viewByteLength = 5; // default to the byteLength of the ArrayBuffer, should be less or equal to the byte length of the ArrayBuffer, immutable
let view = new DataView(buffer, viewStartByteOffset, viewByteLength );
console.log(`\nThe byte length of the DataView is ${view.byteLength}`);
console.log(`The byte offset of the DataView is ${view.byteOffset}`);
- Store at the offset 3 two bytes (ie 16-bit / two's complement signed integer 4)
let value16= 50;
let offset16 = 3; // from 0 to viewByteLength - 2 (because we try to save 2 bytes (ie 16))
view.setInt16(offset16, value16);
console.log(`\nWrite 2 bytes (16bit) at offset ${offset16}`);
console.log(`16bit value is ${view.getInt16(offset16)}`); // 50
- Store at the offset 0, 4 bytes (ie 32 bit with the byte order specificed (little endianess))
offset = 0;
value = 257
let isLittleEndian = false; // default
view.setInt32(offset, value, isLittleEndian);
console.log(`Write 4 bytes (32bit) at offset 0`);
console.log(`32bit value is ${view.getInt32(0)}`); // 257
- The previous operation has overwritten the data of our first operation.
console.log(`\nThe data of the first operation was overwritten:`);
console.log(`16bit value of offset ${offset16} is ${view.getInt16(offset16)}`);
Shorthand Data View Int32Array
- This shorthand view will use set32 32 bit for each bucket in the array
const buffer = new ArrayBuffer(10);
const view = new Int32Array(buffer);