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

I'm doing bitwise manipulation in a project, and I wonder if embedded typed arrays can save me some headache and maybe even give me a little performance boost.

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

Can I use typed arrays to get the same answer?

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

Side question:

It was strange to me that the above uint32- negative - obviously not very ... unsigned, since the var name suggests ...

If I combine binary octets and parse it, I get a free positive answer

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

console.log(uint32)
// 2155971203 
Run code

Not surprisingly, I can modify the process to get the correct values ​​from each, but I don’t understand why procedure 1 is negative, but procedure 2 is positive.

let a = -2138996093;
let b = 2155971203;

// two 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
Run code
+4
1

- DataView - , , - bigendien int32

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 endien
let int32be = dataview.getInt32(0); // second parameter absent or falsey == want big endien
console.log(int32le); // -2088599168
console.log(int32be); // -2138996093

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

SIGNED int, (<<, |) 32-

+2

Source: https://habr.com/ru/post/1654189/


All Articles