7

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.

asked Sep 6, 2016 at 10:17

3 Answers 3

10

For those who want little-endian, you can specify endianness using the DataView class.

let buff = new Uint8Array(4);
buff[0]=0x12;
buff[1]=0x19;
buff[2]=0x21;
buff[3]=0x47;
var view = new DataView(buff.buffer, 0);
view.getUint32(0, true); // true here represents little-endian
David Noreña
4,3103 gold badges30 silver badges43 bronze badges
answered Aug 9, 2020 at 5:10
Sign up to request clarification or add additional context in comments.

Comments

6

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;
}
answered Sep 6, 2016 at 10:56

3 Comments

I found this solution extremely helpful, but I needed to convert from Uint8Array[16] and needed the following change to get it to work: ``` let result = buffer.readUInt32BE(0); ```
just a note that length argument in readUIntBE, which specifies a number of bytes to read, must satisfy 0 < byteLength <= 6. Doc here.
more "manual" way, which should work fine is here: parseInt(buffer.toString('hex',0,7),16). In the first step, buffer is converted to string, using 'hex' encoding, start and stop byte (0 and 7). Then parseInt is used to convert this hex number into decimal...
2

This is one solution:

let Uint8Arr = new Uint8Array(4);
Uint8Arr[0]=0x12;
Uint8Arr[1]=0x19;
Uint8Arr[2]=0x21;
Uint8Arr[3]=0x47;
let buffer = Buffer.from(Uint8Arr);
console.log( buffer.readUInt32BE(0) );
answered Sep 6, 2016 at 10:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.