Game Development Reference
In-Depth Information
var i32View = new Int32Array(buffer);
i32View.length == 8; // True
Here's where things can get a bit confusing. The array buffer works in terms of bytes.
As a refresher, a byte is made up of 8 bits. A bit is a single binary digit, which can
have a value of either zero or one. This is how data is represented at its most basic
format in computers.
Now, if a buffer works in terms of bytes, when we created our buffer in the example,
we created a block of 32 bytes. The view that we create to hold and use the buffer
can be one of nine possible types, each of which specifies a different data size (in
terms of bits, not bytes). Thus, a view of type Int32 represents a buffer where each
element is an integer , 32 bits long. In other words, a 32 bits view can hold exactly
8 bytes (1 byte = 8 bits; 32 bits = 8 bytes), as illustrated in following screenshot:
Array buffers work in terms of bytes. In the image, there are 4 bytes, although view
types work in terms of bits. Thus, if we use a 32 bits view, it will result in an array that
has a length of exactly one element. If the view uses a 16 bits data type, then the
array will have 2 elements (4 bytes divided by 16 bits). Finally, if the view uses an 8
bits data type, the array stored in the 4 bytes buffer will have 4 elements.
Tip
One important thing to always remember is that when you create an array buffer,
the length you choose to make the buffer must divide perfectly into however large
you make the array buffer view. If there is not enough room in the buffer to fit
entire bytes, the JavaScript will throw an error of type RangeError .
In the following image, the buffer is only big enough for 8 bits, all of which must be
occupied by whole bytes. Thus, a view is an 8 bits number which would fit exactly
Search WWH ::




Custom Search