Hello 👋,
In this short article we’ll talk about packing integers into binary data in JavaScript using the Buffer, ArrayBuffer and DataView classes.
Sometimes in JavaScript, it may be necessary to pack the elements of an array into a byte buffer and then create a new numeric array from the buffer’s contents. This can be achieved using the DataView
object in JavaScript.
First, create an array of elements you want to pack, for example:
|
|
Next, create a new ArrayBuffer
of the required size:
|
|
Create a DataView
object using this buffer:
|
|
Loop through each element of the original array, and use the setInt32
method of the DataView
object to pack each element into the buffer:
|
|
Note that the setInt32
method takes three arguments:
- The first argument is the byte offset at which to set the value.
- The second argument is the value to set.
- The third argument is a boolean indicating whether to use little-endian or big-endian byte order.
To create a new numeric array from the buffer’s contents, create a new ArrayBuffer
of the same size as the original buffer:
|
|
Create a new DataView
object using this buffer:
|
|
Loop through each element of the original array again, and use the getInt32
method of the original DataView
object to get the value of each element from the original buffer. Then use the setInt32
method of the new DataView
object to set the same value in the new buffer:
|
|
Finally, create a new numeric array using the new buffer:
|
|
This will give you a new numeric array containing the same values as the original array, packed into a byte buffer.
Another way to accomplish the task is to use the shortcut:
|
|
Thanks for reading!
full code:
|
|