是否可以使用 JavaScript 中的类型化数组将 4x Uint8 转换为 Uint32?

Is it possible to convert from 4x Uint8 into Uint32 using typed arrays in JavaScript?

我正在项目中进行一些按位操作,我想知道内置类型化数组是否可以让我省去一些麻烦,甚至可能给我一些性能提升。

let bytes = [128, 129, 130, 131]
let uint32 = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]
//=> -2138996093

我可以使用类型化数组来获得相同的答案吗?

// not actually working !
let uint8bytes = Uint8Array.from(bytes)
let uint32 = Uint32Array.from(uint8bytes)[0]
//=> ideally i'd get the same value as above: -2138996093

附带问题:

我发现上面的 uint32 是负数很奇怪 – 显然不是很... unsigned 正如 var 的名称所暗示的那样 ...

如果我将二进制八位字节混合在一起并解析它,我会得到肯定的免费回答

//         128          129          130          131
let bin = '10000000' + '10000001' + '10000010' + '10000011'
let uint32 = Number.parseInt(bin,2)

console.log(uint32)
// 2155971203 

毫不奇怪,我可以反转过程以从每个过程中获得正确的值,但我不明白为什么过程 1 为负而过程 2 为正。

let a = -2138996093;
let b = 2155971203;

// two's compliment, right?
console.log(a.toString(2)) // -1111111011111100111110101111101
console.log(b.toString(2)) // 10000000100000011000001010000011

console.log(a >> 24 & 255) // 128
console.log(a >> 16 & 255) // 129
console.log(a >> 8 & 255)  // 130
console.log(a >> 0 & 255)  // 131

console.log(b >> 24 & 255) // 128
console.log(b >> 16 & 255) // 129
console.log(b >> 8 & 255)  // 130
console.log(b >> 0 & 255)  // 131

处理此问题的最佳方法是使用 DataView - 这样您就可以指定要获取的值的字节顺序 - 您的代码正在使用 int32

的 bigendian 值
let bytes = [128, 129, 130, 131];
let uint8bytes = Uint8Array.from(bytes);
let dataview = new DataView(uint8bytes.buffer);
let int32le = dataview.getInt32(0, true); // second parameter truethy == want little endian
let int32be = dataview.getInt32(0); // second parameter absent or falsey == want big endian
console.log(int32le); // -2088599168
console.log(int32be); // -2138996093

原因

let uint32 = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]

returns SIGNED int 是按位运算符 (<<, |) 将值强制转换为带符号的 32 位值