user91579631 user91579631 - 2 months ago 23
Node.js Question

Convert Uint8Array[n] into integer in node.js

I have a variable Uint8Arr of type Uint8Array[4].

Uint8Arr[0]=0x12;
Uint8Arr[1]=0x19;
Uint8Arr[2]=0x21;
Uint8Arr[3]=0x47;


I want to convert
Uint8Arr
into its equivalent integer which is
0x12192147
or
303636807
.

I would like to have a function that can convert Uint8Arr[n] into its equivalent integer and return the result in decimal.

Answer

This solution will solve for Uint8Arr of any length.

function convert(Uint8Arr) {
    var length = Uint8Arr.length;

    let buffer = Buffer.from(Uint8Arr);
    var result = buffer.readUIntBE(0, length);

    return result;
}
Comments