Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a normal array to a Float32Array?

I've found many ways to create a Float32Array from an array, but all of them involve copying all elements. I want to avoid that cost, because the array will never be used again. I just want to cast it. How is that possible?

like image 869
MaiaVictor Avatar asked Jun 06 '14 00:06

MaiaVictor


People also ask

What is float 32 array?

The Float32Array typed array represents an array of 32-bit floating point numbers (corresponding to the C float data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0 .

What is ArrayBuffer in JavaScript?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".

What is typed array in JavaScript?

JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.


1 Answers

It's impossible. A Float32Array is always a different object than a normal array.

If you want to avoid the cost of copying the items, a) don't use a normal array in the first place or b) let your function that uses it work with normal arrays as well.

If you are looking for the "casting" operation, you can just invoke the Float32Array constructor with the normal array:

var arr = [0.3, 1, 2];
var typedArr = new Float32Array(arr);
like image 198
Bergi Avatar answered Oct 01 '22 15:10

Bergi