Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to unpack binary in javascript?

I am trying to port over some existing code from python to javascript, and am unsure how to go about the following line.

var1, var2 = struct.unpack('<II', buf[:8])

It should be getting two ints from a buffer. The buffer starts in binary, but at this point it has been converted to bytes (ie. bytes(buf)).

Example Buffer:

<Buffer 35 8a 0a 24 16 ed ea 42 88 28 b1 20 b1 cf c9 a1 c9 cc 5c 0b 18 b0 70 3a 8c b8 83 ee d6 ca 55 bf f9 75 1c 94 46 8c 17 03 01 00 20 5a 17 be 43 ba 08 a6 ... >
like image 939
codephobia Avatar asked Jan 18 '26 13:01

codephobia


1 Answers

If your buffer is a node.js Buffer:

var buf = new Buffer([0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00]);

console.log(buf.readUInt32LE(0), buf.readUInt32LE(4));

If your buffer is a typed arrays:

let buf = new Uint8Array([0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00]);
    uint32 = new Uint32Array(buf.buffer);

console.log(uint32[0], uint32[1]); // 255 and 65535 on little endian architectures

If your buffer is a standard array:

let buf = [0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF];

let var1 = buf[0] * 0x1000000 + (buf[1] << 16) + (buf[2] << 8) + buf[3],
    var2 = buf[4] * 0x1000000 + (buf[5] << 16) + (buf[6] << 8) + buf[7];

console.log(var1, var2); // 255 and 65535 on all architectures

You might also be interested in destructuring assignment (since ES6):

let var1, var2;
[var1, var2] = [1, 2];
like image 162
le_m Avatar answered Jan 20 '26 03:01

le_m



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!