You can convert to an ArrayBuffer
, copy the data into and then create a byte view of this buffer :
var data = new Float32Array([0.1, 0.2, 0.3]);
var buffer = new ArrayBuffer(data.byteLength);
var floatView = new Float32Array(buffer).set(data);
var byteView = new Uint8Array(buffer);
This function can convert any TypedArray to any other kind of TypedArray :
function convertTypedArray(src, type) {
var buffer = new ArrayBuffer(src.byteLength);
var baseView = new src.constructor(buffer).set(src);
return new type(buffer);
}
Example :
convertTypedArray(new Float32Array([0.5, 0.3, -0.1]), Uint8Array);
Edit
As Ian pointed out in the comment section, you can access the ArrayBuffer
with TypedArray.buffer
, so you can simply do :
var byteArray = new Uint8Array(floatArray.buffer);
Note that doing this, byteArray
and floatArray
will share the same buffer, so modifying byteArray
will modify floatArray
and vice versa.