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.
user6064424
user6064424
asked Sep 6, 2016 at 10:17
user6064424user6064424
3 Answers 3
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
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
therightstuff
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); ```Oddomir
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...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
lang-js