Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting byte[] to ArrayBuffer in Nashorn

How do I convert an array of bytes into ArrayBuffer in Nashorn? I am trying to insert binary data into a pure JavaScript environment (i.e., it doesn't have access to Java.from or Java.to) and so would like to create an instance out an array of bytes.

like image 566
Vivin Paliath Avatar asked Sep 11 '25 09:09

Vivin Paliath


2 Answers

Looks like I was going about this the wrong way. It made more sense to convert it into Uint8Array since what I'm sending in is an array of bytes.

I created the following function:

function byteToUint8Array(byteArray) {
    var uint8Array = new Uint8Array(byteArray.length);
    for(var i = 0; i < uint8Array.length; i++) {
        uint8Array[i] = byteArray[i];
    }

    return uint8Array;
}

This will convert an array of bytes (so byteArray is actually of type byte[]) into a Uint8Array.

like image 66
Vivin Paliath Avatar answered Sep 13 '25 23:09

Vivin Paliath


I think you're right about using a Uint8Array, but this code might be preferable:

function byteToUint8Array(byteArray) {
    var uint8Array = new Uint8Array(byteArray.length);
    uint8Array.set(Java.from(byteArray));
    return uint8Array;
}

Also, if you really need an ArrayBuffer you can use uint8Array.buffer.

like image 34
Robert Tupelo-Schneck Avatar answered Sep 13 '25 22:09

Robert Tupelo-Schneck