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]
Can I use typed arrays to get the same answer?
let uint8bytes = Uint8Array.from(bytes)
let uint32 = Uint32Array.from(uint8bytes)[0]
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
let bin = '10000000' + '10000001' + '10000010' + '10000011'
let uint32 = Number.parseInt(bin,2)
console.log(uint32)
Run codeNot 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;
console.log(a.toString(2))
console.log(b.toString(2))
console.log(a >> 24 & 255)
console.log(a >> 16 & 255)
console.log(a >> 8 & 255)
console.log(a >> 0 & 255)
console.log(b >> 24 & 255)
console.log(b >> 16 & 255)
console.log(b >> 8 & 255)
console.log(b >> 0 & 255)
Run code