Search code examples
javascriptbinarytransmission

Browser read integer from binary string


I have for example here this string

'x���'

Which you may possibly not see depending on the devide you're using. That's the number 2024000250 encoded as a 32 bit signed big endian integer, which I've generated using Node

let buffer = new Buffer(4);
b.writeInt32BE(2024000250).toString();

I'm receiving the 4 bytes in question on the client side but I can't seem to find how to turn them back into an integer...


Solution

  • Well I finally got around to getting this to work.

    It is not quite what I started off with but I'm just gonna post this for some other lost souls.

    It is worth mentioning that ibrahim's answer contains most of the necessary information but is trying to satisfy the XY problem which my question ended up being.

    I just send my binary data, as binary

    let buffer = new Buffer(4);
    buffer.writeInt32BE(2024000250);
    
    // websocket connection
    connection.send(buffer);
    

    Then in the browser

    // message listener
    let reader = new FileReader();
    reader.addEventListener('loadend', () => {
      let view = new DataView(reader.result);
    
      // there goes the precious data
      console.log(view.getInt32());
    });
    reader.readAsArrayBuffer(message.data);
    

    In all honesty this tickles my gag reflex. Why am I using a file reader to get some data out of a binary message? There is a good chance a better way of doing this exists, if so please add to this answer.

    Other methods I found are the fetch API which is no better than the file reader in terms of hack rating and Blob.prototype.arrayBuffer which is not yet supported fully.