Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

295
Vistas
How to convert a Javascript number to a Uint8Array?

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

@Bergi, is something like this what you had in mind?

function numToUint8Array(num) {
  let arr = new Uint8Array(8);

  for (let i = 0; i < 8; i++) {
    arr[i] = num % 256;
    num = Math.floor(num / 256);
  }

  return arr;
}

function uint8ArrayToNumV1(arr) {
  let num = 0;

  for (let i = 0; i < 8; i++) {
    num += Math.pow(256, i) * arr[i];
  }

  return num;
}

function uint8ArrayToNumV2(arr) {
  let num = 0;

  for (let i = 7; i >= 0; i--) {
    num = num * 256 + arr[i];
  }

  return num;
}

let foo = numToUint8Array(9458239048);
let bar = uint8ArrayToNumV1(foo); // 9458239048
let baz = uint8ArrayToNumV2(foo); // 9458239048

console.log(foo, bar, baz);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda