Search code examples
javascripttyping

Cast int array as byte array in Javascript


I'm trying to take an array of integers and cast it to bytes in JavaScript but can't quite figure out how to do it.

The input would look something like [2,-76,7,2,8,69,82,88,87,2,52,50,...].

If I was going to do it in another language like Java I'd use something like the following.

byte[] bytArr = new byte[intArray.size()];
for (int i = 0; i < intArray.size(); i++) {
      bytArr[i] = (byte) intArray[i];
}

I'm pretty new to JS so not sure if this is even possible...


Solution

  • You can use Int8Array, which is a typed array.

    const arr = Int8Array.from([2,-76,7,2,8,69,82,88,87,2,52,50]);