3

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);
1
  • 1
    8 bytes? where are the other 4? Commented Jul 26, 2016 at 15:41

1 Answer 1

6

There 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.