Search code examples
javascriptbinaryconcatenationtyped-arrays

Fastest way to concatenate two JS uint8 arrays to a uint16 array?


I know this is fairly easy in other languages, but what is the best way to do this in JS if I have two arrays of 8-bit unsigned integers, and would like to concatenate them to one array of unsigned 16 bit integers?


Solution

  • Assuming both Arrays have the same length, use a for loop with the bitwise left shift operator <<;

    var arr8A = [2, 3, 4], // example
        arr8B = [5, 6, 7];
    // code start
    var arr16 = new Uint16Array(arr8A.length),
        i;
    for (i = 0; i < arr8A.length; ++i)
        arr16[i] = (arr8A[i] << 8) + arr8B[i];
    arr16;
    

    The reverse is similar but you use the bitwise zero-fill right shift operator >>> and the bitwise AND operator &;

    // arr16 as above
    var arr8A = new Uint8Array(arr16.length),
        arr8B = new Uint8Array(arr16.length),
        i;
    for (i = 0; i < arr16.length; ++i) {
        arr8A[i] = arr16[i] >>> 8;
        arr8B[i] = arr16[i] & 255;
    }
    console.log(arr8A, arr8B);
    

    The maximum size numbers you can safely use these operators with are 32-bit integers.