Binary arrays

Source: Internet
Author: User

Tags: name allow array manipulation data type conversion script Merge self parsing 1 years

Previous words

Binary Arrays (Arraybuffer objects, Typedarray views, and DataView views) are an interface for JavaScript to manipulate binary data. These objects have long existed and are independent specifications (released in February 2011), ES6 incorporated them into the ECMAScript specification and added new methods. This article describes the binary arrays in detail


The original design of a binary array is related to the WEBGL project. The so-called WebGL refers to the interface between the browser and the video card, in order to meet the large and real-time data exchange between JavaScript and the video card, the communication between them must be binary, not the traditional text format. Text format to pass a 32-bit integer, both ends of the JavaScript script and the video card are formatted to convert, it will be very time-consuming. At this point, if there is a mechanism, like the C language, directly manipulate the byte, the 4-byte 32-bit integer, in binary form into the video card intact, the performance of the script will be greatly improved

Binary arrays are born in this context. It is much like a C-language array, allowing developers to manipulate memory directly in the form of array subscripts, greatly enhancing JavaScript's ability to process binary data, making it possible for developers to communicate binary with JavaScript's native interface to the operating system

Binary arrays consist of three types of objects

1. Arraybuffer object: Represents a piece of binary data in memory that can be manipulated by "view". The view deploys an array interface, which means that the memory can be manipulated using an array of methods

2, TypedArray (typed array): A total of 9 types of typed arrays, such as Uint8array (unsigned 8-bit integer) array, Int16array (16-bit integer) array, Float32array (32-bit floating-point) array, etc.

3, DataView (Data View): You can customize the composite format of the view, such as the first byte is Uint8 (unsigned 8-bit integer), the second to third byte is Int16 (16-bit integer), the fourth byte starts Float32 (32-bit floating point), etc. In addition, you can customize the byte order

Simply put, the Arraybuffer object represents the raw binary data, and TypedArray (typed array) is used to read and write binary data of simple types, DataView (Data View) to read and write binary data of complex types

[note] A binary array is not a real array, but a class array object

Many browser-operated APIs use binary arrays to manipulate binary data, such as: File API, XMLHttpRequest, Fetch API, Canvas, WebSockets


The Arraybuffer object represents a piece of memory that stores binary data, it cannot be read directly, and can only be interpreted by Typedarray (typed array) and DataView (Data View) in the specified format.

Note ie9-Browser does not support

Arraybuffer is a constructor that allocates a contiguous area of memory where data can be stored. The parameter length indicates the size of the array buffer to be created, which is the desired memory size in bytes. Finally, a new Arraybuffer object with the specified size is returned. Its contents are initialized to 0

New ArrayBuffer (length)

The following code generates a 32-byte area of memory that needs to be assigned a view in order to read and write this piece of content. For example, the DataView Data View, which is created, needs to provide an Arraybuffer object instance as a parameter. The code creates a DataView view of 32 bytes of memory, and then reads the first element in unsigned 8-bit integer format, resulting in 0 because the original memory of the Arraybuffer object, the default all bits are 0

var buf = new ArrayBuffer (+), var dataView = new DataView (BUF);d ataview.getuint8 (0)//0

Another Typedarray view (typed array), one difference from the DataView Data View is that it is not a constructor, but rather a set of constructors that represent different data formats

var buffer = new ArrayBuffer, var x1 = new Int32array (buffer), x1[0] = 1;var x2 = new Uint8array (buffer); x2[0] = 2;x1[0] 2

The above code establishes two views for the same memory, respectively: A 32-bit signed integer (Int32array constructor) and a 8-bit unsigned integer (Uint8array constructor). Since two views correspond to the same memory, one view modifies the underlying memory, which affects the other view

The constructor of the Typedarray view (typed array), in addition to accepting the Arraybuffer instance as a parameter, can also accept an ordinary array as a parameter, directly allocating memory to generate the underlying Arraybuffer instance, and simultaneously complete the assignment of this memory

var typedArray = new Uint8array ([0,1,2]); typedarray.length//3typedarray[0] = 5;typedarray//[5, 1, 2]

The above code uses the Uint8array constructor of the Typedarray view to create a new unsigned 8-bit integer view. As you can see, Uint8array directly uses an ordinary array as a parameter to complete the assignment of the underlying memory


Arraybuffer the ByteLength property of the instance, returning the byte length of the allocated memory area

var buffer = new ArrayBuffer (+); buffer.bytelength//32

If the allocated memory area is large, it is possible that the allocation failed (because there is not so much contiguous free memory), so it is necessary to check whether the allocation was successful

if (buffer.bytelength = = = N) {//success} else {//failed}

"ArrayBuffer.prototype.slice ()"

The Arraybuffer instance has a slice method that allows a copy of the memory area to be copied to generate a new Arraybuffer object

var buffer = new ArrayBuffer (8), var newbuffer = Buffer.slice (0, 3);

The above code copies the first 3 bytes of the buffer object (starting at 0 and ending with the 3rd byte), generating a new Arraybuffer object. The slice method actually contains two steps, the first step is to allocate a new memory, the second step is to copy the original Arraybuffer object past

The slice method accepts two parameters, the first parameter represents the byte ordinal (including the byte) at which the copy begins, and the second parameter represents the byte ordinal of the copy cutoff (excluding the byte). If the second argument is omitted, the default to the end of the original Arraybuffer object

In addition to slice (), the Arraybuffer object does not provide any method of directly reading and writing memory, only allowing the view to be established on it, and then reading and writing through the view

"Arraybuffer.isview ()"

Arraybuffer has a static method, Isview, that returns a Boolean value that indicates whether the parameter is a Arraybuffer view instance. This method is roughly equivalent to judging the parameter, whether it is a Typedarray instance or an DataView instance

var buffer = new ArrayBuffer (8); Arraybuffer.isview (buffer)//Falsevar v = new Int32array (buffer); Arraybuffer.isview (v)//True

Typed arrays

The Arraybuffer object acts as a memory area and can hold multiple types of data. The same memory, different data have different interpretation, this is called "view". Arraybuffer has two views, a Typedarray view and a typed array. The other is the DataView view, which is also translated into a data view. Array members of the former are the same data type, and the latter array members can be of different data types

Currently, the Typedarray view (typed array) consists of 9 types, each of which is a constructor

Data type  byte length   meaning                             corresponds to C language type Int8       1        8-bit signed integer                      signed charUint8      1        8-bit unsigned integer                    unsigned CHARUINT8C     1        8-bit unsigned integer (auto filter overflow)        unsigned charInt16      2        16-bit signed integer                     shortUint16     2        16-bit unsigned integer                   unsigned shortInt32      4        32-bit signed integer                     intUint32     4        32-bit unsigned integer                  unsigned intFloat32    4        32-bit floating-point                         floatFloat64    8        64-bit                         floating-point number double

These 9 constructors generate arrays, collectively known as Typedarray Views (typed arrays). They are much like normal arrays, with the length property, which can be used with the square bracket operator ([]) to get a single element, and all the methods of the array are available on top of them. The difference between an ordinary array and a Typedarray array is mainly in the following areas

1. All members of the Typedarray array are of the same type

2, the members of the Typedarray array are continuous, there is no vacancy

3, the default value of the Typedarray array member is 0. For example, the new array (10) returns an ordinary array with no members, just 10 slots; new Uint8array (10) returns a Typedarray array with 10 members 0

4, Typedarray array is just a layer of view, itself does not store data, its data are stored in the underlying Arraybuffer object, to get the underlying object must use the Buffer property


The Typedarray array provides 9 constructors to generate an array instance of the corresponding type

Constructors have several uses

1, TypedArray (buffer [, byteoffset [, length]])

The constructor can accept three parameters: the first argument (required): the underlying Arraybuffer object for the view; the second argument (optional): The byte ordinal at which the view starts, the default starting from 0, and the third argument (optional): The view contains the number of data, by default, until the memory area of this section ends

On the same Arraybuffer object, you can create multiple views based on different data types

Create a 8-byte arraybuffervar b = new ArrayBuffer (8);//Create a Int32 view that points to B, starting at byte 0 until the end of the buffer var v1 = new Int32array (b);//Create a pointer to B Uint8 view, starting at byte 2 until the end of the buffer var v2 = new Uint8array (b, 2);//Create a Int16 view that points to B, starting at byte 2, length 2var v3 = new Int16array (b, 2, 2);

The above code generates three views over a length of 8 bytes of memory (b): v1, V2, and v3. Therefore, V1, V2, and V3 are overlapping: v1[0] is a 32-bit integer that points to the byte 0~ byte 3;v2[0] is a 8-bit unsigned integer that points to byte 2;v3[0] is a 16-bit integer that points to byte 2~ byte 3. As long as any one view changes memory, it will be reflected on the other two views.

[Note that the]byteoffset must be consistent with the type of data to be established, or it will error

var buffer = new ArrayBuffer (8), var i16 = new Int16array (buffer, 1);//uncaught rangeerror:start offset of Int16array sho Uld be a multiple of 2

In the above code, a new 8-byte Arraybuffer object is created, and then in the first byte of the object, a signed 16-bit integer view is established, resulting in an error. Because a signed 16-bit integer requires two bytes, the Byteoffset parameter must be divisible by 2

If you want to interpret the Arraybuffer object from any byte, you must use the DataView view (Data View) because the Typedarray view provides only 9 fixed interpretation formats

2, TypedArray (length)

Views can also be generated without directly allocating memory through the Arraybuffer object.

var f64a = new Float64array (8); f64a[0] = 10;f64a[1] = 20;f64a[2] = f64a[0] + f64a[1];

The above code generates a 8-member Float64array Array (a total of 64 bytes), and then assigns each member a value in turn. At this point, the argument to the view constructor is the number of members. As you can see, the assignment operation of the view array is no different than the operation of the normal array.

3, TypedArray (TypedArray)

Typedarray the constructor of an array, you can accept another Typedarray instance as a parameter

var typedArray = new Int8array (new Uint8array (4));

In the above code, the Int8array constructor takes a Uint8array instance as a parameter.

[note] The new array generated at this time, just copy the value of the parameter array, the corresponding underlying memory is not the same. The new array will open up a new set of memory data that will not create a view on the memory of the original array.

var x = new Int8array ([1, 1]); var y = new Int8array (x); x[0]//1y[0]//1x[0] = 2;y[0]//1

In the above code, the array y is generated with the array x as the template, and when x changes, y does not change.

If you want to construct different views based on the same memory, you can use the following notation

var x = new Int8array ([1, 1]), var y = new Int8array (X.buffer), x[0]//1y[0]//1x[0] = 2;y[0]//2

4, TypedArray (Arraylikeobject)

The parameters of the constructor can also be a normal array, and then the Typedarray instance is generated directly

var typedArray = new Uint8array ([1, 2, 3, 4]);

[note] At this point the Typedarray view will re-open the memory and will not establish a view on the memory of the original array

The above code generates an Typedarray instance of a 8-bit unsigned integer from a normal array.

Typedarray arrays can also be converted back to normal arrays

var Normalarray = (TypedArray);

"Static Properties and Methods"


The Bytes_per_element property represents the number of bytes consumed by each element in the strongly typed array

Int8array.bytes_per_element; 1uint8array.bytes_per_element; 1uint8clampedarray.bytes_per_element; 1int16array.bytes_per_element; 2uint16array.bytes_per_element; 2int32array.bytes_per_element; 4uint32array.bytes_per_element; 4float32array.bytes_per_element; 4float64array.bytes_per_element; 8


The Name property is a string value that describes the type array construction name; "Int8array"; "Uint8array"; "Uint8clampedarray"; "Int16array"; "Uint16array"; "Int32array"; "Uint32array"; "Float32array"; "Float64array"

Of ()

static method Typedarray.of () is used to convert a parameter to a Typedarray instance

Float32array.of (0.151,-8, 3.7)//Float32array [0.151,-8, 3.7]

The following three methods will generate the same Typedarray array

Method a Let Tarr = new Uint8array ([three-way]);//Method two Let Tarr = Uint8array.of (All-in-one);//Method Three let Tarr = new Uint8array (3); Tarr[0] = 1;tarr[1] = 2;tarr[2] = 3;

From ()

The static method Typedarray.from () accepts a data structure that can be traversed (such as an array) as a parameter, returning a Typedarray instance based on this structure

Uint16array.from ([0, 1, 2])//Uint16array [0, 1, 2]

This method can also convert one Typedarray instance to another

var ui16 = uint16array.from (Uint8array.of (0, 1, 2)) ui16 instanceof Uint16array//True

The From method can also accept a function as a second parameter that iterates over each element, similar to the map method.

Int8array.of (127, 126). Map (x = 2 * x)//Int8array [-2, -4,-6]int16array.from (Int8array.of (127, 126,), x =& Gt 2 * x)//Int16array [254, 252, 250]

In the above example, the From method does not overflow, indicating that the traversal is not for the original 8-bit integer array. That is, the from will copy the Typedarray array specified by the first parameter into another memory, processing and then turning the result into the specified array format

"Byte order"

BYTE-order refers to the way a number is represented in memory

var buffer = new ArrayBuffer, var int32view = new Int32array (buffer), for (var i = 0; i < int32view.length; i++) {
   int32view[i] = i * 2;}

The code above generates a 16-byte Arraybuffer object and, based on it, establishes a 32-bit integer view. Because each 32-bit integer occupies 4 bytes, you can write a total of 4 integers, in turn 0,2,4,6

If you then create a 16-bit integer view of the data, you can read a completely different result

var int16view = new Int16array (buffer), for (var i = 0, i < int16view.length; i++) {Console.log ("Entry" + i + ":" + in T16view[i]);} Entry 0:0//Entry 1:0//Entry 2:2//Entry 3:0//Entry 4:4//Entry 5:0//Entry 6:6//Entry 7:0

Because each 16-bit integer occupies 2 bytes, the entire Arraybuffer object is now divided into 8 segments. Then, because the computer of the x86 system uses the small end byte order (little endian), the relative important byte is in the memory address of the back, the relative unimportant byte is in the front memory address, therefore obtains the above result

For example, a 16-digit 0x12345678 that occupies four bytes, the most important byte that determines its size is "12", and the least important is "78". The small-endian byte order is the least important byte in front, the storage order is 78563412, the big-endian byte sequence is the opposite, the most important byte is in front, the storage order is 12345678. At present, almost all personal computers are small endian, so the Typedarray array is also used to read and write data in small endian byte sequence, or more accurately, read and write data according to the byte sequence set by the native operating system.

This does not mean that big endian byte-order is unimportant, in fact, many network devices and specific operating systems are using big-endian byte order. This poses a serious problem: if a piece of data is a big endian byte order, the Typedarray array will not parse correctly because it can only handle small endian bytes! To solve this problem, JavaScript introduces the DataView object, which allows you to set the byte order, which is described in detail below

Here's another example

Suppose that a buffer contains the following bytes [0x02, 0x01, 0x03, 0x07]var buffer = new ArrayBuffer (4); var v1 = new Uint8array (buffer); v1[0] = 2;v1[1 ] = 1;v1[2] = 3;v1[3] = 7;var Uint16view = new Uint16array (buffer);//computer with small endian//So the first two bytes equals 258if (uint16view[0] = = 258) {    console.log (' OK ');//"OK"}//assignment operation uint16view[0] = 255;//bytes changed to [0xFF, 0x00, 0x03, 0x07]uint16view[0] = 0xff05;//byte change For [0x05, 0xFF, 0x03, 0x07]uint16view[1] = 0x0210; Bytes changed to [0x05, 0xFF, 0x10, 0x02]

The following function can be used to determine whether the current view is a small-endian byte-order or a

Const Big_endian = symbol (' Big_endian '), const Little_endian = symbol (' Little_endian '), function getplatformendianness ( ) {let    Arr32 = Uint32array.of (0x12345678);    Let arr8 = new Uint8array (arr32.buffer);    Switch ((arr8[0]*0x1000000) + (arr8[1]*0x10000) + (arr8[2]*0x100) + (Arr8[3]) {case    0x12345678:    return Big_ ENDIAN;    Case 0x78563412:    return Little_endian;    Default:        throw new Error (' Unknown endianness ');}    }

In summary, the biggest advantage of the Typedarray array compared to a normal array is that it can manipulate memory directly, without the need for data type conversions, so it's much faster

"Arraybuffer and String Conversions"

Arraybuffer to a string, or to a string to Arraybuffer, there is a premise that the string encoding method is determined. Assuming that the string is UTF-16 encoded (internal encoding of JavaScript), you can write your own conversion function

Arraybuffer to string, parameter is Arraybuffer object function Ab2str (buf) {return String.fromCharCode.apply (null, new Uint16array (buf ));}
The string is converted to a ArrayBuffer object with the argument string function Str2ab (str) {    var buf = new ArrayBuffer (Str.length * 2);//2 bytes per character    var bu Fview = new Uint16array (BUF);    for (var i = 0, strLen = str.length; i < StrLen; i++) {        Bufview[i] = str.charcodeat (i);    }    return BUF;}


The range of values that can be accommodated is determined by the different view types. Beyond this range, an overflow will occur. For example, a 8-bit view can hold only a 8-bit binary value, and if it is placed into a 9-bit value, it overflows

The overflow rule for the Typedarray array is simply to discard the overflow bit and then interpret it according to the view type

var uint8 = new Uint8array (1); uint8[0] = 256;uint8[0]//0uint8[0] = -1;uint8[0]//255

In the above code, UINT8 is a 8-bit view, and a 256 binary form is a 9-bit value of 100000000, and overflow occurs. According to the rules, only the latter 8 bits, or 00000000, are retained. The interpretation rules for the uint8 view are unsigned 8-bit integers, so 00000000 is 0

Negative numbers in the computer using the "2 complement" means, that is, the corresponding positive value of the operation, and then add 1. For example, 1 corresponds to a positive value of 1, after the operation is done, get 11111110, plus 1 is the complement form 11111111. The uint8 interprets 11111111 as an unsigned 8-bit integer, and the return result is 255.

A simple conversion rule that can represent

Forward overflow (overflow): When the input value is greater than the maximum value of the current data type, the result is equal to the minimum value of the current data type plus the remainder value minus 1

Negative overflow (underflow): When the input value is less than the minimum value of the current data type, the result is equal to the maximum value of the current data type minus the residual value plus 1

The "remainder" above is the result of the modulo operation, which is the result of the% operator inside the JavaScript

12% 4//012% 5//2

In the above code, 12 divided by 4 has no residual value, and dividing by 5 will get the remainder 2

var int8 = new Int8array (1); int8[0] = 128;int8[0]// -128int8[0] = -129;int8[0]//127

In the example above, Int8 is a signed 8-bit integer view with a maximum value of 127 and a minimum value of-128. When the input value is 128, it is equivalent to forward overflow 1, according to the "Minimum value plus residual value (128 divided by 127 of the remainder is 1), minus 1" rule, will return 128; The input value is 129, which is equivalent to negative overflow 1, according to the "maximum value minus the remainder (129 divided by 128 of the remainder is 1) Plus the 1 "rule, it will return 127.

The overflow rule for the Uint8clampedarray view differs from the rule above. It specifies that the value is equal to the maximum value of the current data type, that is, 255 if a positive overflow occurs, and that the value is equal to the minimum value of the current data type, or 0, if a negative overflow occurs.

var uint8c = new Uint8clampedarray (1); uint8c[0] = 256;uint8c[0]//255uint8c[0] = -1;uint8c[0]//0

In the example above, uint8c is a uint8clampedarray view that returns 255 on a positive overflow and a negative overflow of 0

"Instance properties and methods"

Normal array operation methods and properties, which are fully applicable to the Typedarray array

Note The Typedarray array does not have a concat method. If you want to merge multiple Typedarray arrays, you can use the following function

function concatenate (resultconstructor, ... arrays) {let    totallength = 0;    For (let arr of arrays) {        totallength + = arr.length;    }    Let result = new Resultconstructor (totallength);    Let offset = 0;    For (let arr of arrays) {        result.set (arr, offset);    Offset + = arr.length;    }    return result;} Concatenate (Uint8array, Uint8array.of (1, 2), Uint8array.of (3, 4))//Uint8array [1, 2, 3, 4]


The buffer property of the Typedarray instance that returns the corresponding Arraybuffer object for the entire memory area. This property is a read-only property

var a = new Float32array, var b = new Uint8array (a.buffer);

A View object and a B view object of the above code, corresponding to the same Arraybuffer object, that is, the same memory


The ByteLength property returns the length of memory occupied by the Typedarray array, in bytes. The Byteoffset property returns the Typedarray array starting from which byte of the underlying Arraybuffer object. Both of these properties are read-only properties

As an example of V3, each data in the Int16array array occupies two bytes, and if allocated to 8 bytes of memory, 4 data can be placed. Since there is an offset of 2 bytes, memory only has 6 bytes left, so you can place 3 data. The third parameter means that only 2 data is placed, the final V3 only two data, each data occupies two bytes, so the bytelength of the V3 array is 2*2=4

var B = new ArrayBuffer (8), var v1 = new Int32array (b), var v2 = new Uint8array (b, 2), var v3 = new Int16array (b, 2, 2); Telength//8v2.bytelength//6v3.bytelength//4v1.byteoffset//0v2.byteoffset//2v3.byteoffset//2


The Length property indicates how many members a Typedarray array contains. Note that the ByteLength property is distinguished from the length property, which is the byte size, which is the member length

var a = new Int16array (8); a.length//8a.bytelength//16

TypedArray.prototype.set ()

The set method of the Typedarray array is used to copy an array (an ordinary array or an Typedarray array), that is, to completely copy a piece of content to another memory

var a = new Uint8array (8), var B = new Uint8array (8); B.set (a);

The above code copies the contents of the a array to the B-array, which is a copy of the entire memory, much faster than the copy-member replication.

The Set method can also accept the second parameter, indicating which member of the B object starts copying a object

var a = new Uint16array (8), var B = new Uint16array (Ten), B.set (A, 2);

The b array of the above code is two more members than the a array, so start copying from b[2]

TypedArray.prototype.subarray ()

The Subarray method is for a part of the Typedarray array, and then a new view is created

var a = new Uint16array (8), var B = a.subarray (2,3); a.bytelength//16b.bytelength//2

The first parameter of the Subarray method is the starting member ordinal, the second argument is the end member ordinal (without the member), and if omitted, all remaining members are included. So, the A.subarray (2,3) of the above code means that B contains only a[2] a member with a byte length of 2

TypedArray.prototype.slice ()

The slice method of the Typearray instance, which can return a new Typedarray instance at a specified location

Let Ui8 = Uint8array.of (0, 1, 2); Ui8.slice ( -1)//Uint8array [2]

In the above code, UI8 is an instance of the 8-bit unsigned integer array view. Its slice method can be used to return a new view instance from the current view.

The parameter of the slice method, which represents the exact location of the original array, starts generating a new array. Negative values indicate the reverse position, that is, 1 is the first position to the bottom, 2 is the second-to-last position, and so on

Composite view

Because the view's constructor can specify the starting position and the length, in the same memory, you can sequentially store different types of data, called the "Composite View"

var buffer = new ArrayBuffer, var idview = new Uint32array (buffer, 0, 1), var usernameview = new Uint8array (buffer, 4, 1 6) var Amountdueview = new Float32array (buffer, 20, 1);

The above code divides a 24-byte-length Arraybuffer object into three pieces:

byte 0 to byte 3: A 32-bit unsigned integer

Byte 4 to byte 19:16 8-bit integer

byte 20 to byte 23:1 32-bit floating-point number

This data structure can be described in the following C language:

struct SomeStruct {unsigned long id;char username[16];float amountdue;};

Data View

If a piece of data includes multiple types (such as HTTP data from a server), you can also work with the DataView view in addition to building a composite view of the Arraybuffer object

The DataView view provides more operational options and supports setting the byte order. Originally, in the design purpose, the Arraybuffer object's various Typedarray views, is used to transmit the data to the network card, the sound card and so on the native device, therefore uses the native byte order to be possible, but the DataView view is designed to handle the data which the network equipment transmits, So big endian byte order or small end byte sequence is self-settable

The DataView view itself is also a constructor that takes a Arraybuffer object as a parameter to generate the view

DataView (ArrayBuffer buffer [, byte start position [, length]]);
var buffer = new ArrayBuffer; var dv = new DataView (buffer);

The DataView instance has the following properties, meaning the same method as the Typedarray instance

DataView.prototype.buffer: Returns the corresponding Arraybuffer object DataView.prototype.byteLength: Returns the occupied memory byte length DataView.prototype.byteOffset: Returns the current view Starting from which byte of the corresponding Arraybuffer object

DataView Instance provides 8 methods of reading memory

GetInt8: Reads 1 bytes, returns a 8-bit integer getUint8: reads 1 bytes, returns an unsigned 8-bit integer getInt16: reads 2 bytes, returns a 16-bit integer getUint16: reads 2 bytes, Returns an unsigned 16-bit integer getInt32: reads 4 bytes, returns a 32-bit integer getUint32: reads 4 bytes, returns an unsigned 32-bit integer getFloat32: reads 4 bytes, Returns a 32-bit floating-point number getFloat64: reads 8 bytes, returns a 64-bit floating-point number

The parameters for this series of Get methods are a byte ordinal (not a negative number, otherwise an error), indicating which byte to start reading from

var buffer = new ArrayBuffer; var dv = new DataView (buffer);
Reads a 8-bit unsigned integer from the 1th byte var v1 = dv.getuint8 (0);//Reads a 16-bit unsigned integer var v2 = dv.getuint16 (1) from the 2nd byte,//reads a 16-bit unsigned integer var v3 = dv from the 4th byte . getUint16 (3);

The above code reads the first 5 bytes of the Arraybuffer object, which has a 8-bit integer and two 16-bit integers.

If you read two or more bytes at one time, you have to be clear about how the data is stored, whether it is a small endian or an end byte sequence. By default, the Get method of DataView uses the big-endian byte-order to interpret the data, and if you need to use a small-endian byte-order interpretation, you must specify true in the second argument of the Get method

Small-endian byte-order var v1 = dv.getuint16 (1, true);//Big endian byte-order var v2 = Dv.getuint16 (3, false);//endian byte-order var v3 = dv.getuint16 (3);

DataView View provides 8 methods of writing memory

SetInt8: Writes a 1-byte 8-bit integer setUint8: Writes a 1-byte 8-bit unsigned integer setInt16: writes 2 bytes of 16-bit integers setUint16: writes 2-byte 16-bit unsigned integers setInt32: writes 4-byte 32-bit integers setUint32: Write 4-byte, 32-bit unsigned integer setFloat32: writes 4 bytes of 32-bit floating-point setFloat64:8-bit floating-point number written to 64 bytes

This series of set methods accepts two parameters, the first parameter is the byte ordinal, which is the byte from which the write begins, and the second parameter is the data written. For those methods that write two or more bytes, you need to specify a third argument, false or undefined to write with a big endian byte order, and true to use a small byte-order write

In the 1th byte, a 32-bit integer with a endian byte order of 25 is written Dv.setint32 (0, 32, false);//In the 5th Byte, a 4-bit integer with a value of 25 is written in the endian byte order Dv.setint32 (25);//In the 9th byte, Writes a 32-bit floating-point number dv.setfloat32 (8, 2.5, true) with a small-endian byte-order value of 2.5;

If you are unsure of the byte order of the computer you are using, you can use the following method to determine

var Littleendian = (function () {    var buffer = new ArrayBuffer (2);    New DataView (buffer). setInt16 (0, N, true);    return new Int16array (buffer) [0] = = = 256;}) ();

If it returns true, it is the small endian byte order;

Binary arrays

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: