I have an array of 4 bytes. 32-bit unsigned little endian.
[ 123, 1, 0, 0]
I need help converting this to an integer. I tried below with no luck:
let arr = [ 123, 1, 0, 0 ];
let uint = new Uint32Array(arr);
console.log('INT :', uint);
I have an array of 4 bytes. 32-bit unsigned little endian.
[ 123, 1, 0, 0]
I need help converting this to an integer. I tried below with no luck:
let arr = [ 123, 1, 0, 0 ];
let uint = new Uint32Array(arr);
console.log('INT :', uint);
Share
Improve this question
edited Jul 26, 2016 at 15:45
Lightness Races in Orbit
386k77 gold badges666 silver badges1.1k bronze badges
asked Jul 26, 2016 at 15:28
DonDon
972 silver badges9 bronze badges
1
- 1 8 bytes? where are the other 4? – dandavis Commented Jul 26, 2016 at 15:41
1 Answer
Reset to default 6There are two ways:
If you know your browser is also little endian (almost always true these days), then you can do it like this:
const bytes = new Uint8Array([123, 1, 0, 0]);
const uint = new Uint32Array(bytes.buffer)[0];
console.log(uint);
If you think your browser might be running in a big endian environment and you need to do proper endian conversion, then you do this:
const bytes = new Uint8Array([123, 1, 0, 0]);
const dv = new DataView(bytes.buffer);
const uint = dv.getUint32(0, /* little endian data */ true);
console.log(uint);