Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

404
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda