Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active March 18, 2021 23:52
Show Gist options
  • Save rpivo/db18c84286554bfa927ecc475e391a56 to your computer and use it in GitHub Desktop.
Save rpivo/db18c84286554bfa927ecc475e391a56 to your computer and use it in GitHub Desktop.
Working With ArrayBuffers & DataViews in Javascript

Working With ArrayBuffers & DataViews in Javascript

// creates an ArrayBuffer with a length of 16 bytes, or 128 bits
const buffer = new ArrayBuffer(16)

// this data cannot yet be read or written. We need a DataView to do that

// available type array views:

// Int8Array / signed 8-bit integer array / -128 to 127

// Uint8Array / unsigned 8-bit integer array / 0 to 255

// Uint8ClampedArray / unsigned 8-bit integer array (clamped) / 0 to 255

// Int16Array

// Uint16Array

// Int32Array

// Uint32Array

// Float32Array

// Float64Array

// BigInt64Array

// BigUint64Array

// We can convert the buffer to readable/writable DataView
const dataview = new Int8Array(buffer)

console.log(dataview)
// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

// We can now mutate the type array
dataview[0] = 100

console.log(dataview)
// [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

// However, the values that we set these integers to must make sense in regards to their data types. 
// Otherwise, we will get unexpected results
dataview[0] = 500

console.log(dataview)
// [-12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment