Yes, there is a simple way without manually recording the loop (the loop still exists somewhere in the background):
new Uint16Array([1,2,3]);
It's all. Of course, floating numbers will be rounded and large numbers will overflow.
Convert a typed array to a buffer
The buffer of any typed array is accessible through the .buffer property, since anyone can read MDN :
new Uint16Array([1,2,3]).buffer;
Choosing the Right Typed Array
We will warn that the mentioned Uint16Array will contain integers (without floating point) between zero and 65535. To save any javascript number 1, you will want to use Float64Array - the largest, only 8 bytes.
1:. This is an unlimited double, which appears to be 64 bit IEEE 754 number
A map has been created here that displays important information related to the types of numerical data:
var NUMBER_TYPE = [ {name: "uint8", bytes:1, max: 255, min: 0, floating: false, array: Uint8Array}, {name: "int8", bytes:1, max: 127, min: -128, floating: false, array: Int8Array}, {name: "uint16", bytes:2, max: 65535, min: 0, floating: false, array: Uint16Array}, {name: "int16", bytes:2, max: 32767, min: -32768, floating: false, array: Int16Array}, {name: "uint32", bytes:4, max: 4294967295, min: 0, floating: false, array: Uint32Array}, {name: "int32", bytes:4, max: 2147483647, min: -2147483648, floating: false, array: Int32Array}, {name: "float64", bytes:8, max: Number.MAX_VALUE, min: Number.MIN_VALUE, floating: true , array: Float64Array} ];
The float 32 is missing, because I could not calculate the necessary information for it. The map, as it is, can be used to compute the smallest typed array you can put in a number:
function findNumberType(num) { // detect whether number has something after the floating point var float = num!==(num|0); // Prepare the return variable var type = null; for(var i=0,l=NUMBER_TYPE.length; i<l; i++) { // Assume this type by default - unless break is hit, every type ends as `float64` type = NUMBER_TYPE[i]; // Comparison asserts that number is in bounds and disalows floats to be stored // as integers if( (!float || type.floating) && num<=type.max && num>=type.min) { // If this breaks, the smallest data type has been chosen break; } } return type; }
Used as:
var n = 1222; var buffer = new (findNumberType(n).array)([n]);
Please note that this only works if NUMBER_TYPE properly ordered.