3

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 ... >
3
  • What does your buffer look like in JavaScript? Uint8Array? Commented Jun 18, 2016 at 0:26
  • 1
    Buffer looks like var buf = new Buffer(0);. It's a packet buffer using cap in nodejs. Commented Jun 18, 2016 at 0:56
  • ^ Please consider including such important information into your question next time Commented Jun 18, 2016 at 2:18

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

2 Comments

It's not giving me an error, but I don't think it is giving me the numbers I am looking for. I added an example buffer to my question.
see updated answer. BTW: if you replace uint32 = new Uint32Array(buf.buffer); with uint32 = new Uint32Array(buf); in the second example where buf is your node.js buffer it should work, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.