最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

32 bit - Converting 32-bit unsigned little endian to integer in javascript - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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);

发布评论

评论列表(0)

  1. 暂无评论