Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

403
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!