I have a Javascript integer (whose precision can go up to 2^53 - 1
), and I am trying to send it over the wire using an ArrayBuffer
. I suppose I could use BigInt64Array
, but the browser support still seems relatively new with that.
I cannot use Int32Array
(which was my original solution), because the precision for that is up to 2^32 - 1
, whereas a Javascript integer can safely go up to 2^53 - 1
. This is my problem.
Is there an easy way to simply turn any Javascript integer into a Uint8Array
of length 8?
For example, I am looking for a function like this:
function numToUint8Array(num) {
let arr = new Uint8Array(8);
// fill arr values with that of num
return arr;
}
let foo = numToUint8Array(9458239048);
let bar = uint8ArrayToNum(foo); // 9458239048
Does something like this exist in the standard library already? If not, is there a way to write something like this?
BigInt64Array
you already mentioned. "Is there a way to write something like this?" - just repeatedly divide by 256 and writenum % 256
as one byte into yourUint8Array
. Make sure to decide on the endianness. – Paleoecologyuint8ArrayToNum
I'm trying to think through it but not sure if I have it right. Going to post an answer. – Incautiousfoo
expected to be for your example? – Gluten