I was asked to convert the integers to 32-bit binary numbers.
So is used integer.toString(2)
and got the required value in 32-bit binary format of 0\'sand 1\'s. But
Now you can use ArrayBuffer
and DataView
. They are native so the performance will be much better if you need to use it very often.
function toBytesInt32 (num) {
arr = new ArrayBuffer(4); // an Int32 takes 4 bytes
view = new DataView(arr);
view.setUint32(0, num, false); // byteOffset = 0; litteEndian = false
return arr;
}
equals to
function toBytesInt32 (num) {
arr = new Uint8Array([
(num & 0xff000000) >> 24,
(num & 0x00ff0000) >> 16,
(num & 0x0000ff00) >> 8,
(num & 0x000000ff)
]);
return arr.buffer;
}
which use javascript bitwise operators to achieve that.