понедельник, 12 декабря 2011 г.

Typed Arrays and ArrayBuffers

Typed Arrays provide a means to look at raw binary contents of data through a particular typed view. For example, if we want to look at our raw binary data a byte at a time, we can use a Uint8Array (Uint8 describes an 8-bit unsigned integer value, commonly known as a byte). If we want to read the raw data as an array of floating point numbers, we can use a Float32Array (Float32 describes a 32-bit IEE754 floating point value, commonly known as a floating point number). The following types are supported:
Array Type Element size and description
Int8Array8-bit signed integer
Uint8Array8-bit unsigned integer
Int16Array16-bit signed integer
Uint16Array16-bit unsigned integer
Int23Array32-bit signed integer
Uint32Array32-bit unsigned integer
Float32Array32-bit IEEE754 floating point number
Float64Array64-bit IEEE754 floating point number
Each array type is a view over an ArrayBuffer. The ArrayBuffer is a reference to the raw binary data, but it does not provide any direct way to interact with the data. Creating a TypedArray view of the ArrayBuffer provides access to read from and write to the binary contents.
The example below creates a new ArrayBuffer from scratch and interprets its contents in a few different ways:
// Create an 8 byte buffer
var buffer = new ArrayBuffer(8);

// View as an array of Uint8s and put 0x05 in each byte
var uint8s = new Uint8Array(buffer);
for (var i = 0; i < 8; i++) {
uint8s[i] = 5; // fill each byte with 0x05
}

// Inspect the resulting array
uint8s[0] === 5; // true - each byte has value 5
uint8s.byteLength === 8; // true - there are 8 Uint8s

// View the same buffer as an array of Uint32s
var uint32s = new Uint32Array(buffer);

// The same raw bytes are now interpreted differently
uint32s[0] === 84215045 // true - 0x05050505 == 84215045
In this way, Typed Arrays can be used for tasks such as creating floating point values from their byte-level components or for building data structures that require a very specific layout of data for efficiency or interoperation.

Комментариев нет:

Отправить комментарий