1

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...

LockieR
  • 370
  • 6
  • 19
  • 2
    Does this answer your question? [Java byteArray equivalent in JavaScript](https://stackoverflow.com/questions/30797862/java-bytearray-equivalent-in-javascript) – Charlie Bamford Jul 02 '21 at 00:43
  • JS isn't typed. – 0xLogN Jul 02 '21 at 00:44
  • What would be the purpose? JavaScript does have optimized integer array types, but most of the time you just uses plain arrays of `Number`. Are you trying to save memory? Truncate off the high bytes? Something else? – ShadowRanger Jul 02 '21 at 00:44
  • 1
    @LoganDevine: JS isn't *statically* typed, and the typing system is more weak than not, but it is typed, and there are [special array types for this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) when you need it. – ShadowRanger Jul 02 '21 at 00:45

1 Answers1

1

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]);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80