I have a byte array:
[101, 97, 115, 121] # ['e', 'a', 's', 'y']
How can I interpret it as a packed binary? Something like struct.Struct(format).unpack in Python:
>>> import struct
>>> s = struct.Struct('>1I') # a big-endian, two-byte, unsigned int
>>> s.unpack('easy')
(1700885369,)
Is there a way to implement this in JavaScript without an import?
There is no built-in way to do this in JavaScript. However, there are various ports of Python’s struct module which you can use to exactly copy the functionality, e.g. jspack.
If you only want to have a single (or a few) operations though, you can easily implement it yourself:
var bytes = [101, 97, 115, 121];
var unpacked = bytes.reduce(function (s, e, i) { return s | e << ((3 - i) * 8); }, 0);
console.log(unpacked); // 1700885369
That is essentially a fancy way of doing this:
121 | 115 << 8 | 97 << 16 | 101 << 24
or written using the indices:
bytes[3] | bytes[2] << ((3-2) * 8) | bytes[1] << ((3-1) * 8) | bytes[0] << ((3-0) * 8)
And the other way around:
var number = 1700885369;
var bytes = [];
while (number > 0) {
bytes.unshift(number & 255);
number >>= 8;
}
console.log(bytes); // [101, 97, 115, 121]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With