Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpreting bytes as packed binary data in JavaScript

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?

like image 395
Zach Gates Avatar asked Sep 28 '26 09:09

Zach Gates


1 Answers

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]
like image 188
poke Avatar answered Sep 29 '26 22:09

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!