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

402
Vistas
How to pack data to byte array in java script?

I have one int16 variable (2 bytes) and an int32 vaiable(4 bytes). And I want to pack this two variables to js byte array. I can do it so:

<script>
    var int16_1 = 10;
    var int32_1 = 20;
    var buffer = new ArrayBuffer(8);
    var buf_1 = new Int16Array(buffer,0,1);
    var buf_2 = new Int32Array(buffer,4,1);
    buf_1[0]=int16_1;
    buf_2[0]=int32_1;
    console.log(buffer);
</script>

In this case I have output:

ArrayBuffer(8)
byteLength: 8
[[Prototype]]: ArrayBuffer
[[Int8Array]]: Int8Array(8)
0: 10
1: 0
2: 0           <-extra use byte
3: 0           <-extra use byte
4: 20
5: 0
6: 0
7: 0

But in this case I need to use extra 2 bytes.

If I try to do so:

<script>
    var int16_1 = 10;
    var int32_1 = 20;
    var buffer = new ArrayBuffer(6);
    var buf_1 = new Int16Array(buffer,0,1);
    var buf_2 = new Int32Array(buffer,2,1);
    buf_1[0]=int16_1;
    buf_2[0]=int32_1;
    console.log(buffer);
</script>

I have an error: Uncaught RangeError: start offset of Int32Array should be a multiple of 4 at new Int32Array ()

If I try to do so:

<script>
    var int16_1 = 10;
    var int32_1 = 20;
    var buffer = new ArrayBuffer(6);
    var buf_1 = new Int16Array(buffer,0,1);
    var buf_2 = new Int32Array(buffer.slice(2),0,1);
    buf_1[0]=int16_1;
    buf_2[0]=int32_1;
    console.log(buffer);
</script>

I have wrong output:

ArrayBuffer(6)
byteLength: 6
[[Prototype]]: ArrayBuffer
[[Int8Array]]: Int8Array(6)
0: 10
1: 0
2: 0
3: 0
4: 0
5: 0

Is there any way to pack different size data to byte array without extra usage of memory?

about 4 years ago · Juan Pablo Isaza
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