javascript - 在javascript中将32位无符号小端转换为整数

标签 javascript 32-bit

我有一个 4 字节的数组。 32 位无符号小端。

[ 123, 1, 0, 0]

我需要帮助将其转换为整数。我在下面尝试但没有运气:

let arr = [ 123, 1, 0, 0 ];
let uint = new Uint32Array(arr);
console.log('INT :', uint);

最佳答案

有两种方式:

如果您知道您的浏览器也是小字节序的(现在几乎总是如此),那么您可以这样做:

const bytes = new Uint8Array([123, 1, 0, 0]);
const uint = new Uint32Array(bytes.buffer)[0];
console.log(uint);

如果您认为您的浏览器可能在大端环境中运行并且您需要进行适当的字节序转换,那么您可以这样做:

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

关于javascript - 在javascript中将32位无符号小端转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38594076/

相关文章:

c - 没有 free() 调用 malloc() 的真正后果是什么?它会使程序变得疯狂,例如永远循环吗?

javascript - puppeteer 师夏普 : setting a fake path when loading content?

javascript |数组转换

java - 尝试构建 32 位 JD2XX DLL 时找不到 -lftd2xx

java - 将四个 32 位整数转换为 java 中的 IP 地址

python - 使用python 64位运行32位程序

Javascript:图像转为 localStorage 的 base64

javascript - 操纵 JavaScript 数组

javascript - 使用 jsonp 和 php 返回回调

java - 64 位操作系统上的 32 位 Java : is there a limit to number of JVMs?