codeWonderland
codeWonderland

Reputation: 407

How do I pack unsigned integers in js?

tl;dr - I need a working js equivalent to struct.pack("!I", <num_here>)

I'm trying to create an electron frontend for a python chat server I built a while back. When I built said server, I set it up so that all of the data was in json, and when it was sent it was prefixed with the length of the message, packed via struct.pack, so that I could determine when I got all of the data. So if I had '{"USERNAME" : "codeWonderland"}' I would prefix it with \x00\x00\x00\x1e

I found the library bufferpack, but it keeps returning \x00\x00\x00\x00 every time I use the pack operation. There are also a ton of forks of this library, but all of the changes are arbitrary. Furthermore, I wold try and fix the library myself, but literally every variable is just a single letter, so it is very difficult to parse.

Is there any way to accomplish this packing in an easier way? I don't really need to worry about unpacking, because I can quite literally just use the json on the js side when I recieve it from the server, trimming off the length from the string and parsing it normally.

Upvotes: 2

Views: 233

Answers (1)

Jason Kleban
Jason Kleban

Reputation: 20788

How about this?

const output = document.getElementById('output');

function bigEndianOf(n)
{
    return Uint8Array.from([
        (n & 0xFF000000) >>> 24,
        (n & 0x00FF0000) >>> 16,
        (n & 0x0000FF00) >>>  8,
        (n & 0x000000FF) >>>  0,
    ]);
}

document.getElementById('text').addEventListener('change', e => {
  const prefix = new TextDecoder('utf-8').decode(bigEndianOf(e.target.value.length));
  output.value = prefix;
})
text: <input id="text" /><br />
length prefix string: <input id="output" readonly />

Upvotes: 1

Related Questions