ArrayBuffer
ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes. i.e. byte array
ArrayBuffer 是内存中一段固定长度的连续数据存储区的引用,你无法直接操作或修改它。但你可以通过创建一个 TypedArray 或者 DataView 来操作ArrayBuffer。
TypedArray 与 DataView 都可以被看作是一种 View 。对于 View,一般的,我们用 eyeglasses 来形容它,即不同颜色眼镜看到的物体颜色甚至形状都不甚相同。我们可以创建红色的或者蓝色的镜片,甚至是哈哈镜。
TypedArray, a view into an ArrayBuffer where every item has the same size and type.
DataView, another view into an ArrayBuffer, but one which allows items of different size and type in the ArrayBuffer
TypedArray 为某一种固定 size 的数据格式
而 DataView 则可以使用多种 TypedArray 来表示数据
ArrayBuffer 的创建
const AB1 = new ArrayBuffer()
alert(AB1.byteLength)// 注意,以下列表中的属性为 dev tool 为便捷调试而自动添加的属性
// 实际使用中并不存在
[[Int8Array]]
[[Int16Array]]
[[Int32Array]]
[[Uint8Array]]
TypedArray objects
// basic
var buffer = new ArrayBuffer(8);
var view = new Int32Array(buffer);// 'hello world!' converted to utf-8 code
const arr = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
let u8 = new Uint8Array(arr)
// [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]
let i8 = new Int8Array(u8.buffer)
// [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]
let u16 = new Uint16Array(u8.buffer, 0, u8.buffer.byteLength / 2)
// [25960, 27756, 8303, 28535, 27762, 8548]
let i16 = new Int16Array(u8.buffer, 0, u8.buffer.byteLength / 2)
// [25960, 27756, 8303, 28535, 27762, 8548]
DataView
Multi-byte number formats are represented in memory differently depending on machine architecture — see Endianness for an explanation. DataView
accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness.
// basic
const arr = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
let u8 = new Uint8Array(arr)
view.getUint8(0)
// 104// getUint16(byteOffset [, littleEndian])
// Indicates whether the 16-bit int is stored in little- or big-endian format. If false or undefined, a big-endian value is read.
view.getUint16(0,false);
// 26725
// 0110 1000 0110 0101
// 104 101view.getUint16(0,true);
// 25960
// 0110 0101 0110 1000
// 101 104dv.setUint8(0,72);
dv.setUint8(6,87);
[...u8].map(item=>String.fromCharCode(item)).join('')
// "Hello World!"// setInt16(0, 256, true /* littleEndian */);
后续
参考:
https://zh.wikipedia.org/wiki/%E5%AD%97%E8%8A%82%E5%BA%8F
https://hacks.mozilla.org/2017/01/typedarray-or-dataview-understanding-byte-order/